.NET Casting Generic List

JMD is half correct. In fact, it’s absolutely incorrect to say that we will be able to cast a generic list with C# 4.0. It’s true that covariance and contravariance will be supported in C# 4.0 but it will only works with interface and delegate and there will have a lot of constraints. Therefore, it won’t work with List.

The reason is really simple.

If B is a subclass of A, we cannot say that List<B> is a subclass of List<A>.

And here’s why.

List<A> exposes some covariances methods (returning a value) and some contravariances methods (accepting a value as a parameter).

e.g.

  • List<A> exposes Add(A);
  • List<B> exposes Add(B);

If List<B> inherits from List<A>…than you would be able to do List<B>.Add(A);

Therefore, you would loose all type safety of generics.

Leave a Comment