Understanding Covariance and Contravariance in C#


Covariance and contravariance features were introduced in C# 4.0. Covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.

For example, in the case of generics, Covariance allows casting of generic types to base types, for example, IEnumerable<A> will be implicitly convertible to an IEnumerable<B> if A can implicitly be converted to B and Contravariance reverses it.

// List of string

IList<string> arrNames = new List<string>();

// Convert it to IEnumerable collection of objects

IEnumerable<object> objects = arrNames;

Here are some detailed articles on the same topic.

Covariance And Contravariance in C#
This article provides an overview of Covariance and Contravariance.

C# 4.0 New Features - Straight to the Point (Part 2)
This article discusses three other features of C#: New Compiler options, Dynamic and Covariance and Contravariance with examples.

Assignment Compatibility, Covariance and Contravariance
The terms covariance and contravariance enable implicit references to conversion of array type, delegate type, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.

Look at Covariance and Contravariance in Delegates
In this article, we will look into Covariance and Contravariance in Delegates using C#.


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.