January 14

Contravariance in C#

0  comments

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.

 


Tags


You may also like

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Subscribe to our newsletter now!

Get instant access to the Master C# 9 webinar to learn all the new exciting C# 9 features quickly.
Get regular videos and news on C# and .NET and offers on products and services to master C#.

We will collect, use and protect your data in accordance with our Privacy Policy.

>