Why is C # arrays covariant and what benefits does it bring?

I am 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 in order, but it will be unceremonious and perhaps not surprising to explode at runtime.

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

+7
arrays c # covariance
source share
3 answers

Eric Lippert says:

Unfortunately, this type of covariance is broken. It was added to the CLR because Java requires this, and CLR developers wanted to be able to support Java-like languages. Then we added it to C # because it was in the CLR. At that time, this decision was rather controversial, and I am not very happy with it, but now we can do nothing about it.

+12
source share
+4
source share

There are many situations in which code will move or copy elements between slots in an array. Provided that Arr is a one-dimensional array with at least two elements, the following code will work regardless of the type of Arr or the elements contained in it.

 Object temp = Arr[1]; Arr[1] = Arr[0]; Arr[0] = temp; 

This code will be ineffective if Arr is the value type, but since temp read from the array, the array type is guaranteed to hold such a value. The code will need to insert and unlock elements of type value and thus be inefficient with such types, but it will work independently.

Please note that when creating arrays, covariant is one of the ways to allow things like sorting methods, for arbitrary types of arrays, this is not the only one. Another approach would be to have System.Array include several methods and properties whose parameters are not related to the type of the underlying element. For example, it may include some simple methods such as Swap , CopyItem and Roll , and possibly methods for performing more complex permutations based on a list of indexes. Note that unlike the code shown above, a type of type Int[] can override its Swap method in such a way as to avoid boxing and unpacking.

+1
source share

All Articles