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.
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.


Sharing is Caring