Question

I'm studying about covariance and contravariance in C#.

I understand it quite a bit already but I'm looking for some more technical details. I understand that because of array covariance I can implicitly cast string [] array = new string[1] to object [] moreGeneralArray = array.

Storing an int in this array will then throw ArrayTypeMismatchException.

I'm looking on a bit more technical details as to how this is checked? It appears that there is still somewhat of a type hidden behind the object [] type that tells the runtime it's actually a string array?

Was it helpful?

Solution

When you implicitly cast an object of type string[] to object[], the backing store is still of type string[].

According to Eric Lippert, this particular kind of covariance is broken. He sais that 'It was added to the CLR because Java requires it and the CLR designers wanted to be able to support Java-like languages.'

Read more on his blog.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top