Problem understanding covariance contravariance with generics in C#
The error message is insufficiently informative, and that is my fault. Sorry about that.
The problem you are experiencing is a consequence of the fact that covariance only works on reference types.
You're probably saying "but IA
is a reference type" right now. Yes, it is. But you didn't say that T
is equal to IA
. You said that T
is a type which implements IA
, and a value type can implement an interface. Therefore we do not know whether covariance will work, and we disallow it.
If you want covariance to work you have to tell the compiler that the type parameter is a reference type with the class
constraint as well as the IA
interface constraint.
The error message really should say that the conversion is not possible because covariance requires a guarantee of reference-type-ness, since that is the fundamental problem.
I just wanted to complement Eric's excellent insider answer with a code example for those that may not be that familiar with generic constraints.
Change Something
's signature like this: The class
constraint has to come first.
public static IList<T> Something<T>(IEnumerable<T> foo) where T : class, IA