Question about C# covariance

Simply put, IList<T> is not covariant, whereas IEnumerable<T> is. Here’s why…

Suppose IList<T> was covariant. The code below is clearly not type-safe… but where would you want the error to be?

IList<Apple> apples = new List<Apple>();
IList<Fruit> fruitBasket = apples;
fruitBasket.Add(new Banana()); // Aargh! Added a Banana to a bunch of Apples!
Apple apple = apples[0]; // This should be okay, but wouldn't be

For lots of detail on variance, see Eric Lippert’s blog post series on it, or watch the video of my talk about variance from NDC.

Basically, variance is only ever allowed where it’s guaranteed to be safe (and in a representation-preserving way, which is why you can’t convert IEnumerable<int> into IEnumerable<object> – the boxing conversion doesn’t preserve representation).

Leave a Comment