I have been reading up on the changes that .NET4.5 will bring, and on this blog post I stumbled upon something I neither knew nor understood.
When talking about the implementation of readonly collections, Immo Landwerth says:
Unfortunately, our type system doesn’t allow making types of T covariant unless it has no methods that take T as an input. Therefore, we can’t add an IndexOf method to IReadOnlyList. We believe this is a small sacrifice compared to not having support for covariance.
From my obviously limited understanding, it seems like he is saying that in order to enable us to call a method that requires an IReadOnlyList<Shape> by passing in a IReadOnlyList<Circle>, we can’t have a IReadOnlyList<T>.IndexOf(T someShape) method.
I don’t see how the type system would prevent that. Can someone explain?
Suppose
CircleimplementsIEquatable<Circle>. That would naturally be used byIReadOnlyList<Circle>.IndexOfif it were available. Now if you could write this:that would end up trying to pass a
SquaretoCircle.Equals(Circle)which would clearly be a bad idea.The rules which enforce the “no values of
Tin input positions” are in section 13.1.3 of the C# 4 spec. You should also read Eric Lippert’s blog series on generic variance for a lot more details.