Contravariance in C#

Contravariance is a new feature introduced with the version 4 of the C# language.

The definition

Assuming A is implicitly convertible to B,  X is contravariant when 
X<B> is implicitly convertible to X<A> 

or similarly

X is contravariant if X<B> can be cast to X<A> if B subclasses A

From C# 4, generic interfaces support it for type parameters marked with the in modifier. This is supported when the generic type parameter only appears in input positions, designed with the in modifier.

While covariance is intuitive, contravariance seems useless and wrong.

However, it makes sense and there are situations when is useful.
One example is the IEquatityComparer<T> interface that has been changed using the in modifier.
Example
Suppose that we have the following classes.

Thanks to contravariance 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.

 

Permanent link to this article: https://www.productivecsharp.com/2013/01/contravariance-in-c/


Warning: in_array() expects parameter 2 to be array, null given in /home/andreaa9/public_html/wp-content/themes/graphene/inc/plugins.php on line 92
>