January 14

Covariance in C# 4

2  comments

Covariance for generics interfaces is a new feature introduced with the version 4 of the C# language.

The definition 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 A

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.

IEnumerable is covariant

Example

Suppose that we have two classes in a inheritance relationship.

Two classes in an inheritance relationship

Thanks to this new feature of the language, the following code compiles and works as expected.

Covariance in action

 

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 it in arrays and delegates.


Tags


You may also like

  • Hi Ian, thank you for the reply. You are right.

    I 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

  • {"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.

    >