liveBook · Manning

Contravariance

As explained in Fabulous Adventures in Data Structures and Algorithms

Contravariance is a type-system relationship in which a more-derived type parameter can substitute for a less-derived type parameter in input positions.

Contravariance reverses the assignment direction associated with a type relationship. If a Giraffe is an Animal, an interface that accepts Animals can be used where an interface accepting Giraffes is expected: it already handles every Giraffe. section 7.3

abstract class Animal : Object {}
class Giraffe : Animal {}
class Tiger : Animal {}
interface IC<in T> 
{
    int CompareTo(T item1, T item2);
}

The C# interface marks its type parameter with `in`, documenting that T appears only in input positions. section 7.3

Animal comparer assigned as a giraffe comparer

An IC<Animal> can be assigned to an IC<Giraffe>. The comparer promises to compare any two Animals, so it can safely accept two Giraffes. The apparently backward conversion is the defining surprise: the type argument moves from Giraffe to Animal while the interface relationship points in the opposite direction. section 7.3

Viewed categorically, types are objects and assignment compatibility is a morphism. Mapping T to IC<T> preserves those morphisms while reversing their direction, making IC<T> a contravariant endofunctor. section 7.3 section 7.4

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Explains input positions, reversed assignments, and categorical morphisms, but treats category theory as only a surface-level introduction.
Examples
Uses Animal, Giraffe, and Tiger types with an IC<T> comparison interface and an IC<Animal> to IC<Giraffe> assignment.
What it assumes
Assumes familiarity with types, interfaces, generic parameters, and assignment compatibility while introducing categorical morphisms.
What you can do after
Evaluate type assignments involving C# contravariant interfaces and explain their reversed compatibility using input positions.
How it connects
Connects generic interfaces with covariance, contravariant functors, assignment compatibility, categories, and posetal type relationships.

Also explained in

Compare how 2 books explain contravariance →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.