Monday, 14 January 2013

Contravariance in C#


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

The definition of Contravariance
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
Contravariance in C# 4

From C# 4, generic interfaces support contravariance 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.


No comments:

Post a Comment

What you think about this post? I really appreciate your constructive feedback (positive and negative) and I am looking forward to start a discussion with you on this topic.