Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 182 ยท Generics

Covariance and Contravariance

Understand C# covariance and contravariance with out and in, IEnumerable of T, Func and Action variance, the array covariance trap and variant interfaces.

A Cat is an Animal. So is a List<Cat> a List<Animal>? Intuition says yes, and intuition is wrong in a way that matters: if it were allowed, you could add a Dog to what is secretly a list of cats. Yet IEnumerable<Cat> can be used as an IEnumerable<Animal>, and an Action<Animal> can be used where an Action<Cat> is expected. The rules behind these answers are called variance, and once you see the one idea underneath, it stops being confusing.

This lesson builds that idea from the ground up: what "assignable" means for generic types, why most generics are invariant, how out (covariance) and in (contravariance) relax that safely, which framework types use them, how to declare your own variant interfaces, and the old array-covariance trap you should know about.

The setup: Animal and Cat

All examples use this small hierarchy:

C#
class Animal { public string Name { get; init; } = ""; }
class Cat : Animal { }
class Dog : Animal { }

Ordinary inheritance gives you assignment compatibility: Animal a = new Cat(); is fine, because a cat can do anything an animal can. Variance is the question of whether that compatibility carries over to types built from Cat and Animal, such as List<Cat>, IEnumerable<Cat> or Func<Cat>.

Why List of Cat is not a List of Animal (invariance)

By default, generic types are invariant: List<Cat> and List<Animal> are unrelated. Here is the compile error, and why it protects you:

C# Invariance of List (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler says error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<Cat>' to 'System.Collections.Generic.List<Animal>'. A List<T> both produces T values (the indexer getter, enumeration) and consumes T values (Add, the indexer setter). Treating List<Cat> as List<Animal> is safe for reading but unsafe for writing, so the language refuses both.

Covariance: out means "only produces T"

Suppose a type only ever gives out values of T and never takes one in. Then substituting a more specific type is safe: if you promise "I give you animals" and the actual source gives cats, nobody is surprised. This is covariance, marked with out on the type parameter, and it follows the direction of inheritance: Cat to Animal becomes IEnumerable<Cat> to IEnumerable<Animal>.

C# IEnumerable is covariant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

PrintNames takes IEnumerable<Animal> and happily accepts lists of cats or dogs. Without covariance, you would need a copy (cats.Cast<Animal>().ToList()) or a generic method. IEnumerable<T>, IEnumerator<T>, IReadOnlyList<T>, IReadOnlyCollection<T>, IQueryable<T> and Func<..., TResult> are all covariant in the type that comes out.

Covariance also applies to method return types of delegates, so a method returning Cat fits a delegate returning Animal:

C# Func is covariant in its result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Contravariance: in means "only consumes T"

Now the opposite. Imagine a type that only ever takes in values of T. A handler that can process any Animal can certainly process a Cat, so an Action<Animal> can stand in for an Action<Cat>. The direction reverses: a more general consumer replaces a more specific one. This is contravariance, marked with in.

C# Action and IComparer are contravariant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Contravariance feels odd at first, so use the producer/consumer mnemonic: an out parameter marks a producer (covariant, direction preserved), an in parameter marks a consumer (contravariant, direction reversed). Library examples of in: Action<in T>, Predicate<in T>, Comparison<in T>, IComparer<in T>, IEqualityComparer<in T>, IComparable<in T> and IObserver<in T>.

A quick table to hold the rule:

Kind Keyword Direction Safe because Example
Invariant none no conversion T is used for both input and output List<T>, IList<T>
Covariant out Cat becomes Animal T only comes out IEnumerable<out T>, Func<out TResult>
Contravariant in Animal becomes Cat T only goes in Action<in T>, IComparer<in T>

Func with both: the input and output rule

A function type has both roles at once, and the language gets it right automatically. Func<in T, out TResult> is contravariant in its parameter and covariant in its result:

C# Input and output together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the assignment as: "I need a function that takes a Cat and gives back an Animal." The provided function takes any Animal (so a Cat is fine) and returns a Cat (which is an Animal). Both ends are safe.

Declaring your own variant interfaces

Only interfaces and delegates can be variant. You add out or in to a type parameter, and the compiler verifies that you use it only in matching positions: out T may appear only in output positions such as return types, and in T only in input positions such as method parameters. Here are a producer and a consumer:

C# A covariant and a contravariant interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

What if you break the rule? Add a method to the covariant interface that takes a T:

C# Breaking the variance rule (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler stops you with error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'IBox<T>.Set(T)'. 'T' is covariant. It has detected that the interface both produces and consumes T, and variance would not be safe. The fix is usually to split the interface into a read side and a write side, like IReadOnlyList<out T> and IList<T> do in the library. Splitting interfaces by role (reader/writer, producer/consumer) is the main design technique for variance.

Rules and limits

  • Variance applies only to reference-type type arguments. IEnumerable<int> is not an IEnumerable<object>, since int needs boxing, which changes the representation. (IEnumerable<string> to IEnumerable<object> is fine.)
  • Classes and structs are always invariant. List<T> cannot be variant; use the interface (IEnumerable<T>, IReadOnlyList<T>).
  • The conversion is an identity-preserving reference conversion: no copy is made. The same object is seen through a different interface.
  • out/in parameters of a method (a different use of the words, as in int.TryParse(s, out n)) have nothing to do with variance keywords on type parameters.
  • Two unrelated delegate types with the same signature are never convertible to each other; variance only relates different constructions of the same generic delegate, like Action<Animal> and Action<Cat>.
C# Value types do not vary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The array covariance trap

Arrays have a historical quirk: Cat[] converts to Animal[], copying the reference without copying the array. That is covariance without the out safety check, and it was added to C# 1.0 before generics. It makes the earlier problem real, but moves the detection from compile time to run time:

C# Array covariance (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The program ends with Unhandled exception. System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. Every store into a reference-type array has a hidden type check to catch this (a small cost), which is yet another reason to prefer List<T> and the read-only interfaces over passing arrays around as a more general type. Rule of thumb: read from an Animal[] that is really a Cat[] freely, never write to it.

Variance in practice

  • Accept the most general read-only shape. Methods that only read should take IEnumerable<T> or IReadOnlyList<T>; callers can then pass collections of any derived type.
  • Return the most specific type you can, because return positions are covariant: callers can still store the result in a base-typed variable.
  • Write comparers and handlers once for the base type. An IEqualityComparer<Animal> works for dictionaries keyed by Cat.
  • Design interfaces by role. If an interface mixes T in and out, split it; the two halves can each be variant.
  • Watch generic method inference with variance. A call like Merge(cats, animals) may infer T as Animal thanks to covariance, which can surprise you; specify Merge<Cat>(...) if you meant otherwise.

Variance is also why LINQ methods taking IEnumerable<T> work smoothly on sequences of more specific types.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can't a List<Cat> be assigned to a List<Animal>?

    List<T> is invariant. It consumes T in Add and produces T in the indexer, so neither covariance nor contravariance is safe.
  2. 2. Which assignment is allowed because IEnumerable<out T> is covariant?

    Covariance lets a producer of cats be used as a producer of animals. The reverse direction needs contravariance, int is a value type and List is invariant.
  3. 3. Given Action<in T>, which assignment compiles?

    A handler for any Animal can handle a Cat, so it can stand in for an Action<Cat>. The direction of the conversion is reversed (contravariance).
  4. 4. What happens at run time with Cat[] cats = ...; Animal[] animals = cats; animals[0] = new Dog();?

    Array covariance compiles, but each reference-type array store is checked at run time; storing a Dog into a Cat[] throws ArrayTypeMismatchException.
  5. 5. How do you fix an interface IBox<out T> that has both T Get() and void Set(T value)?

    T appears in input and output positions (error CS1961). Splitting by role gives IReader<out T> and IWriter<in T>, each of which can be variant.

Summary

  • Invariant by default: List<Cat> is not a List<Animal>, because a type that both reads and writes T can't be substituted safely.
  • Covariance (out T) is for producers: IEnumerable<Cat> converts to IEnumerable<Animal>, and Func<Cat> converts to Func<Animal>.
  • Contravariance (in T) is for consumers: Action<Animal> converts to Action<Cat>, IComparer<Animal> converts to IComparer<Cat>.
  • Only interfaces and delegates can be variant, only for reference-type arguments; the compiler checks your usage (CS1961).
  • Arrays are covariant for historical reasons and check every store at run time; avoid writing through a base-typed array reference.
  • Design variant APIs by splitting interfaces into producer and consumer roles; accept IEnumerable<T> or IReadOnlyList<T> for read-only input.

Next: Generic Math and Static Abstract Members