The definition of Covariance for Generics Interfaces
Assuming A is convertible to B, X is covariant if X<A> is implicitly convertible to X<B>or similarly
X is covariant if X<A> can be cast to X<B> if B subclasses ACovariance for Generics Interfaces in C# 4
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.
Example
Suppose that we have two classes in a inheritance relationship.
Thanks to covariance 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 arrays covariance and delegates covariance.
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.
ReplyDeleteEric 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.
ReplyDeleteI 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.
Thanks