Covariance and Contravariance

Rules for when a more specific or more general type can stand in for another.

What is Covariance and Contravariance?

Covariance lets you use a more specific type than asked for where values come out (a list of Cats can be read as a list of Animals). Contravariance lets you use a more general type where values go in (an Animal handler can handle Cats).

IEnumerable<Cat> cats = new List<Cat>();
IEnumerable<Animal> animals = cats;      // covariance

Action<Animal> feed = a => a.Eat();
Action<Cat> feedCat = feed;              // contravariance

Level: Master · More OOP terms at this level

Updated