Covariance for generics interfaces is a new feature introduced with the version 4 of the C# language.
The definition for Generics Interfaces
Assuming A is convertible to B, X is covariant if X<A> is implicitly convertible to X<B>
X is covariant if X<A> can be cast to X<B> if B subclasses A
From C# 4, generic interfaces support covariance for type parameters marked with the out modifier. This modifier ensures that covariance with interfaces is fully type-safe.
Covariance in interfaces is something that is typically consumed. It’s less common that you need to write variant interfaces.
The implementation of IEnumerable in the framework has been changed using the out modifier and this makes all the collections in the base class library covariant.
Suppose that we have two classes in a inheritance relationship.
Thanks to this new feature of the language, the following code compiles and works as expected.
If you use a previous version of C# the code does not compile and generates a build error.
It is worth noting that previous versions of C# already supported it in arrays and delegates.
Variance is a more general concept than just use with generic interfaces. C# supported variance in some ways before C# 4, such as in arrays. The new feature for C# 4 is co/contravariance specifically with generics.
Eric Lippert wrote a long series of blog posts explaining variance and C# prior to C# 4, which I recommend if you want to know more: http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx
Hi Ian, thank you for the reply. You are right.
I was aware of other types of covariance but I wanted only to focus on the new feature of C# 4.
I updated the post in order to make it more clear.