1.10 — Generics¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.9 Polymorphism · Next: 1.11 Delegates
Markers: ⭐ 🧠 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- Generics let you write code once and use it with any type, without giving up type safety and without boxing.
- Constraints (
where T : ...) tell the compiler whatTis allowed to be, so you can actually do things with it. - Covariance (
out) lets you use a more derived type where a base type is expected. Contravariance (in) is the opposite. Only interfaces and delegates support them.
The concept¶
Imagine you need a list of integers, a list of strings, and a list of orders. Without generics you have three bad options:
- Write
IntList,StringListandOrderListby hand — the same code three times. - Write one
ObjectListthat holdsobject— but then everything gets boxed (see 1.1), you lose type checking, and you have to cast everything back on the way out. - Use generics.
Generics let you write the list once, with a placeholder for the type:
One implementation. Full type checking. No boxing. That combination is why generics exist.
Think of T as a blank space in a form. You write the form once, and each person fills in
the blank differently.
How it works¶
Generic classes and methods¶
public class Box<T>
{
private T? _item;
public void Put(T item) => _item = item;
public T? Take() => _item;
}
var intBox = new Box<int>();
intBox.Put(42);
int value = intBox.Take(); // no cast needed — compiler knows it is an int
intBox.Put("hello"); // COMPILE ERROR — caught before you run
That last line is the point. With an object-based version, this would compile fine and
then crash at runtime with an invalid cast. Generics move the error from runtime to compile
time.
Generic methods work the same way, and the compiler can usually work out the type for you:
public static T? FirstOrDefault<T>(IEnumerable<T> items)
{
foreach (var item in items) return item;
return default;
}
var n = FirstOrDefault(new[] { 1, 2, 3 });
// You did not write FirstOrDefault<int>. The compiler
// worked out T = int from the argument. This is called type inference.
Constraints — telling the compiler what T can do¶
By default the compiler knows almost nothing about T, so you can barely use it:
public T Largest<T>(T a, T b)
{
return a > b ? a : b;
// ERROR. The compiler does not know T supports '>'.
// T could be anything, including a type with no comparison.
}
A constraint narrows what T is allowed to be, which lets the compiler allow more:
public T Largest<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b; // now this is fine
}
The constraints you should know:
| Constraint | Means |
|---|---|
where T : class |
must be a reference type |
where T : struct |
must be a value type |
where T : new() |
must have a public constructor with no parameters |
where T : SomeClass |
must be that class or inherit from it |
where T : ISomeInterface |
must implement that interface |
where T : notnull |
cannot be a nullable type |
where T : U |
must be, or inherit from, another type parameter |
You can combine them, but the order is fixed: class/struct first, then base class, then
interfaces, then new() last.
public class Repository<T> where T : Entity, IAuditable, new()
{
public T Create() => new T(); // allowed because of new()
}
Covariance and contravariance¶
This is the part people find hardest, so here it is slowly.
The question being answered is: if Dog is an Animal, is List<Dog> a List<Animal>?
The natural guess is yes. The correct answer is no, and here is why:
List<Animal> animals = new List<Dog>(); // Imagine this were allowed
animals.Add(new Cat()); // Perfectly legal — Cat is an Animal
// But the actual list is a List<Dog>. We just put a Cat in it.
Allowing it would break type safety. So by default, generics are invariant — List<Dog>
and List<Animal> are simply unrelated types.
But sometimes it is safe, and that is what out and in are for.
Covariance — out — safe when you only ever take things OUT.
public interface IEnumerable<out T> { /* ... */ }
IEnumerable<Animal> animals = new List<Dog>(); // ALLOWED
This is safe because IEnumerable<T> only lets you read. There is no Add. If you can
only take dogs out and treat them as animals, nothing can go wrong.
Contravariance — in — safe when you only ever put things IN.
public interface IComparer<in T> { int Compare(T x, T y); }
IComparer<Dog> dogComparer = new AnimalComparer(); // ALLOWED
This looks backwards at first. Read it as: something that can compare any two animals is certainly capable of comparing two dogs. A more general tool can always do a more specific job.
A memory aid that works:
out= output = you take values out = covariant (more derived is fine).in= input = you put values in = contravariant (more general is fine).
Two important limitations: this only works on interfaces and delegates, never on
classes. And it only works for reference types — IEnumerable<int> is not an
IEnumerable<object>, because that would need boxing.
Code¶
A realistic generic repository, which is a very common interview example:
public interface IRepository<T> where T : class, IEntity
{
Task<T?> GetAsync(Guid id, CancellationToken ct);
Task<IReadOnlyList<T>> ListAsync(CancellationToken ct);
Task AddAsync(T entity, CancellationToken ct);
}
public class EfRepository<T>(AppDbContext db) : IRepository<T>
where T : class, IEntity
{
public Task<T?> GetAsync(Guid id, CancellationToken ct)
=> db.Set<T>().FirstOrDefaultAsync(e => e.Id == id, ct);
public async Task<IReadOnlyList<T>> ListAsync(CancellationToken ct)
=> await db.Set<T>().AsNoTracking().ToListAsync(ct);
public async Task AddAsync(T entity, CancellationToken ct)
=> await db.Set<T>().AddAsync(entity, ct);
}
Why the constraints are there:
class— becausedb.Set<T>()in EF Core requires a reference type.IEntity— so we can rely one.Idexisting. Without it,e.Idwould not compile.
Registering it in DI uses an open generic registration — one line covers every entity type:
builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
// Now anyone can inject IRepository<Order>, IRepository<Customer>, etc.
See 6.8.
Interview questions¶
Q: Why do generics exist? What problem do they solve?
Before generics, a collection that could hold anything had to store object. That caused
three problems. Value types got boxed, meaning a heap allocation for every number you
stored. You lost type safety, so putting a string into what you thought was a list of
numbers compiled fine and crashed later. And you had to cast everything on the way out,
which is noisy and can fail. Generics solve all three at once — one implementation, checked
at compile time, with no boxing.
Q: What are generic constraints and why do you need them?
A constraint tells the compiler what a type parameter is allowed to be, using
where T : something. You need them because by default the compiler assumes T could be
literally any type, so it will not let you do much with it — you cannot compare it,
construct it, or call any method beyond what object provides. Adding
where T : IComparable<T> lets you compare. Adding where T : new() lets you construct
one. The constraint buys you capability.
Q: Explain covariance and contravariance.
By default generics are invariant — List<Dog> is not a List<Animal>, because if it were
you could add a Cat to it through the base-typed reference and break type safety.
Covariance, marked with out, allows the more derived version where the base is expected,
and it is only safe when the type only ever produces values — which is why IEnumerable<T>
has it and List<T> does not. Contravariance, marked with in, is the reverse: it allows
a more general type where a specific one is expected, which is safe when the type only
consumes values, like IComparer<T>. The memory aid is that out means output so covariant,
in means input so contravariant. Both only work on interfaces and delegates, and only for
reference types.
Q: Why does IEnumerable<int> not convert to IEnumerable<object>?
Because variance only works for reference types. Converting an int to an object requires
boxing, which changes the actual representation in memory. Variance is built on the fact
that a reference to a derived type is already a valid reference to the base type, with no
conversion needed. That does not hold for value types.
Traps ⚠️¶
- Generics are invariant by default.
List<Dog>is not aList<Animal>and never will be. - Variance only works on interfaces and delegates. You cannot put
outorinon a class type parameter. - Variance does not work for value types.
IEnumerable<int>is not anIEnumerable<object>. default(T)is not alwaysnull. For a value type it is zero, for aboolit isfalse, for a struct it is a struct with all fields zeroed. Usedefaultrather thannullin generic code.- You cannot use most operators on an unconstrained
T. No+, no>, no==in the way you expect. Static abstract interface members (C# 11) are the modern answer to generic maths. - Constraint order is fixed.
classorstructfirst, then a base class, then interfaces, thennew(). The compiler will reject any other order.
Related¶
- 1.1 Boxing — the problem generics were invented to fix
- 1.8 Interfaces — generic interfaces and where variance applies
- 2.1 Collection interfaces —
IEnumerable<out T>in practice - 6.8 Open generic registration — registering
IRepository<>in DI - 13.19 Generic repository — and whether you should build one