liveBook · Manning

In position

As explained in Fabulous Adventures in Data Structures and Algorithms

An input position is a type-parameter occurrence where values of the parameterized type are accepted or consumed rather than produced.

An input position is a type-parameter occurrence where values are accepted or consumed rather than produced. In C#, a comparison interface uses its parameter only as method inputs, so it can declare contravariance with `in`. section 7.3

Why the assignment reverses

A comparer that accepts any Animal can compare two Giraffes. Therefore an `IC<Animal>` may be assigned to an `IC<Giraffe>` variable, even though a Giraffe is assignable to Animal in the opposite direction. The type mapping reverses the direction of the original type relationship. section 7.3

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

Inspect the minimal C# declaration: `CompareTo` consumes `T`, and `IC<in T>` marks the interface as contravariant. section 7.3

public void M(IC<Animal> ica)
{
    IC<Giraffe> icg = ica; #1
}

View the concrete assignment from `IC<Animal>` to `IC<Giraffe>`. section 7.3

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Explains consumed type parameters, demonstrates assignment compatibility, and connects reversed mappings to category-theoretic arrows.
Examples
Uses animal comparers, Giraffe and Animal types, and the `IC<in T>` interface.
What you can do after
Apply contravariance by declaring an input-only interface parameter with the C# `in` modifier.
How it connects
Connects input positions to contravariance, type assignment compatibility, and category theory.

Also explained in

Compare how 2 books explain in position →

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.