views:

94

answers:

2

Hi all,

I'm having trouble understanding why arrays in C# are covariant and what benefits this covariance can bring. Consider the following trivial code example:

object[] myArray = new string[1];
myArray[0] = 1;

This code will compile okay, but will unceremoniously and perhaps unsurprisingly explode at runtime.

If I try to attempt this same thing using generics, the compiler would grumble at me and I would realise my stupidity at an early stage, so my question is this: Why does the C# compiler allow this covariance with arrays and furthermore, what are the potential benefits?

+4  A: 

Eric Lippert has a writeup about this (Actually a long series about 'variance', 11 parts I think)

http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx

And some more interesting stuff

http://blogs.msdn.com/b/ericlippert/archive/2009/09/24/why-is-covariance-of-value-typed-arrays-inconsistent.aspx

Chad
mquander wins for quoting the blog instead of just linking to it.
Jon B
@Jon B - and for quoting the _relevant_ bit.
Oded
Thanks for the links to additional information. Very useful.
nukefusion
+8  A: 

Eric Lippert says:

Unfortunately, this particular kind of covariance is broken. It was added to the CLR because Java requires it and the CLR designers wanted to be able to support Java-like languages. We then up and added it to C# because it was in the CLR. This decision was quite controversial at the time and I am not very happy about it, but there’s nothing we can do about it now.

mquander