Generics: The One Size Mould

Generics: The One Size Mould in C#: A foundry that needed a bronze gear, a steel gear and an aluminium gear could carve three moulds — three sets of drawings,…

The Analogy: The Mould, Not the Casting

A foundry that needed a bronze gear, a steel gear and an aluminium gear could carve three moulds — three sets of drawings, three chances to get a tooth profile wrong, and three moulds to re-cut when the design changes. Or it could carve one mould shaped like a gear and pour whichever metal the order calls for. The shape is the reusable thing; the material is chosen at pour time.

A generic type is that mould. List<T> is not a list of anything in particular — it is the shape of a list, with a hole labelled T where the element type goes. The moment you write List<string>, the mould is filled and you have a real type that holds strings and nothing else. Write List<int> and you get a different real type from the same drawings.

The alternative is what C# had before version 2.0: ArrayList, a list of object, which is the foundry casting everything in lead and painting it to look like bronze. Anything fits, so nothing is checked; every value type is boxed onto the heap on the way in, and every read needs a cast that can fail at runtime. Generics moved that failure from run time to compile time, and that is the entire point of them.


Syntax or Core Structure

A type parameter in angle brackets after the name, used anywhere a type could go: fields, parameters, return types.

using System;
using System.Collections.Generic;

// One mould. T is chosen by whoever creates a Crate.
class Crate<T>
{
    private readonly List<T> items = new();

    public int Count => items.Count;

    public void Pack(T item) => items.Add(item);

    public T Unpack()
    {
        if (items.Count == 0)
            throw new InvalidOperationException("Crate is empty.");

        T last = items[^1];
        items.RemoveAt(items.Count - 1);
        return last;
    }

    public bool TryPeek(out T? item)
    {
        bool any = items.Count > 0;
        item = any ? items[^1] : default;
        return any;
    }
}

class Program
{
    // A generic METHOD: T is inferred from the argument, no angle brackets needed.
    static void Describe<T>(T value) =>
        Console.WriteLine(typeof(T).Name + ": " + value);

    static void Main()
    {
        var words = new Crate<string>();
        words.Pack("mould");
        words.Pack("cast");
        Console.WriteLine(words.Unpack() + " " + words.Count);

        var numbers = new Crate<int>();     // a different type, same drawings
        numbers.Pack(41);
        numbers.Pack(42);
        Console.WriteLine(numbers.Unpack() + " " + numbers.Count);

        Describe(7);
        Describe("seven");
        Describe(7.5);
    }
}

Output:

cast 1
42 1
Int32: 7
String: seven
Double: 7.5

words.Unpack() returns a string and numbers.Unpack() returns an int — no cast at either call site, and numbers.Pack("oops") would not compile. Note also what the compiler did for Describe: you never wrote Describe<int>(7), because type parameters on methods are inferred from the arguments. Type parameters on classes never are; new Crate("mould") is not legal C#.


Technical Depth: What the Mould Costs and Buys

Against the object alternative

ArrayList (object)List<T>
Wrong type addedCompiles, fails laterCompile error
Reading an elementCast requiredAlready typed
Storing 1,000 ints1,000 heap allocations (boxing)One contiguous int buffer
Reading 1,000 ints1,000 unbox operationsDirect reads
What the reader learns"a list of something""a list of ints"

The performance gap is not a micro-optimisation. Boxing an int allocates an object header plus the value, so a million-element ArrayList<int>-style collection produces a million short-lived objects for the garbage collector to sweep, while List<int> is one array of four-byte slots.

Generics are real at run time

C# generics are reified: the closed type exists in metadata and the runtime knows it.

Console.WriteLine(typeof(List<int>) == typeof(List<string>));   // False
Console.WriteLine(typeof(List<>).GetGenericArguments().Length); // 1
Console.WriteLine(new List<int>().GetType().Name);              // List`1

That is a genuine difference from Java, where generics are erased by the compiler and a List<String> is just a List at run time — which is why Java cannot have List<int> and cannot ask a list what it holds. In C#, typeof(List<>) is the open type (the empty mould) and typeof(List<int>) is a closed one; MakeGenericType closes an open type at run time, which is how serializers and containers build types they never saw at compile time.

Under the hood the JIT shares one machine-code body across every reference-type instantiation, because all references are the same size, and generates a specialised body per value type so List<int> really does store raw integers. You get type safety with no indirection, which is what makes generics cheap enough to use everywhere.

Static state is per closed type

Each closed type is its own type, with its own statics:

static class Counter<T>
{
    private static int count;
    public static int Next() => ++count;
}

Counter<int> and Counter<string> keep separate counters. This is occasionally exactly what you want — a per-type cache or id sequence — and occasionally a baffling bug when you expected one shared value.

default and the trouble with an unknown T

Inside a generic type you know almost nothing about T, so the operations you can perform are deliberately few. default is the escape hatch for "whatever empty means here" — null for a reference type, 0 for int, false for bool, an all-zero struct for anything else. That is why if (item == null) is the wrong emptiness test for an unconstrained T, and why comparing two values needs a helper rather than an operator:

// == on an unconstrained T compares references, not contents.
public bool Contains(T candidate)
{
    foreach (T item in items)
        if (EqualityComparer<T>.Default.Equals(item, candidate))
            return true;
    return false;
}

EqualityComparer<T>.Default picks up IEquatable<T> when the type implements it and falls back to Equals, with no boxing for value types. Comparer<T>.Default does the same job for ordering. Arithmetic used to be simply impossible on T; since .NET 7, where T : INumber<T> unlocks +, - and friends through static abstract interface members.

Getting inference back with a static factory

Because class type parameters are never inferred, the standard trick is a non-generic sibling whose generic methods do the inferring — exactly how Task/Task<T> and Tuple/Tuple<T> are shaped:

static class Result
{
    public static Result<T> Ok<T>(T value) => Result<T>.Success(value);
}

var r = Result.Ok(42);          // Result<int>, no angle brackets typed

A generic type and a non-generic type may share a name, because arity is part of the identity.

Variance: when Crate<Derived> is a Crate<Base>

Never, for a class — generics are invariant by default, and List<Dog> is not a List<Animal>. If it were, someone could add a Cat to your list of dogs. Interfaces can opt in where it is provably safe:

DeclarationNameDirectionExample
out TCovariantOnly comes outIEnumerable<Dog> is an IEnumerable<Animal>
in TContravariantOnly goes inIComparer<Animal> is an IComparer<Dog>
TInvariantBothIList<T>, List<T>

Arrays are the historical exception: Dog[] is assignable to Animal[], and writing a Cat into it throws ArrayTypeMismatchException at run time. That check on every array store is a cost every .NET program pays for a design mistake predating generics.


Real World Example: A Result That Carries Any Payload

Throwing for expected failures is expensive and easy to forget to catch. A Result<T> makes "worked, here is the value" and "failed, here is why" the same return type — and generics are what let one implementation serve an int, a decimal and a string without three copies.

using System;

readonly struct Result<T>
{
    private readonly T? value;

    public bool Ok { get; }
    public string Error { get; }

    private Result(bool ok, T? value, string error)
    {
        Ok = ok;
        this.value = value;
        Error = error;
    }

    public static Result<T> Success(T value) => new(true, value, "");
    public static Result<T> Failure(string error) => new(false, default, error);

    public T Value => Ok ? value! : throw new InvalidOperationException("No value: " + Error);

    // A generic method on a generic type: the payload type may change, the failure survives.
    public Result<TNext> Map<TNext>(Func<T, TNext> next) =>
        Ok ? Result<TNext>.Success(next(Value)) : Result<TNext>.Failure(Error);

    public override string ToString() => Ok ? "Ok(" + Value + ")" : "Err(" + Error + ")";
}

// Non-generic sibling, purely so callers get type inference.
static class Result
{
    public static Result<T> Ok<T>(T value) => Result<T>.Success(value);
}

static class Counter<T>
{
    private static int count;
    public static int Next() => ++count;
}

class Program
{
    static Result<int> ParseQuantity(string raw) =>
        int.TryParse(raw, out int n) && n > 0
            ? Result.Ok(n)
            : Result<int>.Failure("not a positive number: " + raw);

    static Result<decimal> LineTotal(string raw, decimal unitPrice) =>
        ParseQuantity(raw).Map(q => q * unitPrice);

    static void Main()
    {
        foreach (string input in new[] { "3", "0", "many" })
            Console.WriteLine(input.PadRight(6) + " -> " + LineTotal(input, 9.99m));

        // Same mould, a completely different payload.
        Result<string> name = Result.Ok("Desk Lamp");
        Console.WriteLine(name.Map(s => s.Length));

        // Statics live per closed type, not per generic definition.
        Console.WriteLine(Counter<int>.Next() + " " + Counter<int>.Next() + " " + Counter<string>.Next());
    }
}

Output:

3      -> Ok(29.97)
0      -> Err(not a positive number: 0)
many   -> Err(not a positive number: many)
Ok(9)
1 2 1

LineTotal never mentions a failure path, yet a bad quantity reaches the caller intact: Map transformed an int result into a decimal result on the success branch and copied the error across on the other. Because Map is generic in its own right, Result<int> became Result<decimal> and Result<string> became Result<int> with one implementation and no casts anywhere.

The last line is the per-type-statics rule in action: two calls into Counter<int> return 1 and 2, while Counter<string> starts again at 1. Useful for a per-type id sequence or metadata cache, and a real trap if you assumed count was one variable — the generic definition is drawings, and each closed type gets its own physical mould with its own state.


Common Mistakes

  1. Reaching for object instead of a type parameter. A method taking object and casting inside is a generic method that forgot to say so: it boxes value types and moves type errors to run time.
  2. Expecting a + b to compile for an unconstrained T. The compiler only allows what every possible type supports. Constrain with where T : INumber<T> (.NET 7+) or take a Func<T, T, T>.
  3. Comparing with == inside a generic type. For an unconstrained T that is reference identity, so two equal strings can compare unequal. Use EqualityComparer<T>.Default.Equals.
  4. Treating default(T) as null. For Crate<int> it is 0, an entirely valid element, so item is null is not an emptiness test. Return a bool from TryPeek and let the caller decide.
  5. Assuming static fields are shared. Cache<Order> and Cache<Customer> have separate statics — including separate locks, which quietly changes what your synchronisation protects.
  6. Expecting inference on constructors. new Crate("mould") does not compile; only methods infer. Add a static factory if the angle brackets are noisy.
  7. Assuming variance. Passing a List<Dog> where List<Animal> is wanted fails. Declare the parameter as IEnumerable<Animal> and the covariance is already there.
  8. Genericising for its own sake. A Repository<T> that only ever closes over one type, or a type parameter used exactly once, adds ceremony and no safety. Generics pay off when the algorithm is identical and only the type differs.

Best Practices

  • Use T for a single parameter and descriptive names — TKey, TValue, TResult — as soon as there are two, so call sites read correctly.
  • Let the compiler prove element types: prefer List<T>, Dictionary<TKey, TValue> and generic methods over anything that traffics in object.
  • Accept the widest interface you can (IEnumerable<T>) and return the most useful concrete or read-only type (IReadOnlyList<T>) from public APIs.
  • Route equality and ordering through EqualityComparer<T>.Default and Comparer<T>.Default, or accept a comparer so callers can override it.
  • Add a non-generic sibling with static factory methods when constructor angle brackets dominate call sites, mirroring Task/Task<T>.
  • Use where T : notnull on dictionary-like keys and where T : struct where boxing would defeat the point — constraints document intent as much as they enable code.
  • Reach for typeof(T) sparingly: a runtime type switch inside a generic method usually means the design wanted an interface or an overload.
  • Keep one implementation for one shape. If the body would genuinely differ per type, that is polymorphism's job, not a type parameter's.

Practice Exercises

  1. Write Pair<TFirst, TSecond> holding two values, with a Swap() method returning Pair<TSecond, TFirst>. Prove with printouts that swapping a Pair<string, int> yields a Pair<int, string>.
  2. Write static T[] Repeat<T>(T value, int count) and call it for an int, a string and a DateTime without ever writing an explicit type argument. Then explain in a comment why new Crate(value) could not work the same way.
  3. Implement RingBuffer<T> with a fixed capacity that overwrites the oldest item when full, using default correctly for empty slots. Demonstrate it with capacity 3 and five items pushed.
  4. Build static class Id<T> handing out sequential ids, and show that Id<Order> and Id<Customer> number independently. Then make one shared sequence and describe what you had to change.