liveBook · Manning

Assignment compatibility

As explained in Fabulous Adventures in Data Structures and Algorithms

Assignment compatibility is the C# type-system rule determining whether an expression of one type may be assigned to a variable of another type.

Assignment compatibility asks whether an expression of type X may be assigned to a variable of type Y. In the type hierarchy, that relation acts like an arrow from X to Y: a Giraffe can be assigned to Animal or Object, but not to Tiger. section 7.2

Covariant generic interfaces

A generic interface does not automatically inherit the assignment relationships of its type argument. An IE<Giraffe> cannot initially be assigned to IE<Animal>. Declaring the type parameter with out makes the interface covariant, because T appears only as an output: IE<Giraffe> can then be assigned to IE<Animal>. section 7.2

Contravariant generic interfaces

Input-only type parameters reverse the direction. With IC<in T>, an IC<Animal> can be assigned to an IC<Giraffe>: a comparer capable of handling every Animal can also handle Giraffe values. The generic construction preserves assignment relationships while reversing their arrows. section 7.3

This perspective connects ordinary C# assignments with category theory. Types serve as objects, assignment compatibility serves as a morphism, and generic interfaces can behave as covariant or contravariant endofunctors. The resulting type relationships form a partial order rather than a single hierarchy: Giraffe and Tiger are incomparable even though both relate to Animal. section 7.2 section 7.4

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Defines the relation, works through covariant and contravariant interfaces, and stops short of a broader programming-language analysis.
Examples
Uses Animal, Giraffe, Tiger, IE<T>, and IC<T> to demonstrate ordinary, covariant, and contravariant assignments.
What it assumes
Assumes C# types and generic interfaces, while defining category terminology through assignment relationships.
What you can do after
Understand why subtype assignments and generic interface assignments can preserve or reverse type relationships.
How it connects
Connects assignment compatibility to covariance, contravariance, generic interfaces, functors, posets, and partial orders.

Also explained in

Compare how 3 books explain assignment compatibility →

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.