C# Interview Question #106

What is covariance and contravariance in C# generics?

Types, Equality, Immutability & Internals Senior Advanced

Quick Interview Answer

Variance controls how generic types relate when their type arguments have an inheritance relationship.

Detailed Explanation

Variance controls how generic types relate when their type arguments have an inheritance relationship.

Covariance uses the out modifier and allows a more derived type to be used where a less derived type is expected. IEnumerable<T> is covariant.

Contravariance uses the in modifier and allows a less derived input type to be used where a more derived input type is expected. Comparer-style and action-style interfaces or delegates often use contravariance.

Variance applies only to reference types and only to appropriately declared generic interfaces and delegates.

Code Example

IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings; // Covariance

Action<object> printObject = o => Console.WriteLine(o);
Action<string> printString = printObject; // Contravariance