I just don’t get something in the .NET generic type casting.
Can someone explain what happens in the following code snippet?
void Main()
{
IEnumerable<int> ints = new List<int>();
IEnumerable<string> strings = new List<string>();
var rez1=(IEnumerable<object>)ints; //runtime error
var rez2=(IEnumerable<object>)strings; //works
var rez3=(List<object>)strings; //runtime error
}
Let’s start with the second line which is easiest.
That cast works because the type parameter of
IEnumerable<T>is now covariant (that’s what theoutinout Tdoes). This means you can cast anIEnumerable<Derived>to anIEnumerable<Base>freely.The first line, which would seem to be the same case, does not work because
intis a value type. Interface variance does not work with value types at all because value types do not really inherit fromSystem.Object; they can be boxed into anobject, but that’s not the same. The documentation mentions thatFinally, the third line does not work because the type parameter of
List<T>is invariant. You can see there is noouton its type parameter; the rules disallow that becauseList<T>is not an interface: