The Analogy: The Hire Agreement
A tool hire counter will lend a trailer to "any vehicle" right up until the moment someone arrives in a hatchback with no tow bar. So the agreement gets fine print: any vehicle with a tow bar rated to 1,400 kg. That single line does two jobs at once — it turns away the vehicles that would fail, and it promises the counter staff that whatever drives up can be hooked to a trailer.
A generic constraint is that fine print. T on its own is a promise of almost nothing: you cannot compare two values of it, cannot construct one, cannot call anything beyond the handful of members every type in .NET has. Add where T : IComparable<T> and the mould now refuses types that cannot be ordered — and in exchange, the code inside may call CompareTo.
That trade is the whole idea, and it runs in both directions. Every constraint narrows who may use your type and widens what you may do inside it. The skill is picking the loosest fine print that still lets the body compile, because a constraint you did not need is a caller you turned away for nothing.
Syntax or Core Structure
Constraints follow the parameter list in a where clause, one per type parameter, comma-separated:
using System;
interface IHasId { int Id { get; } }
class Sensor : IHasId
{
public int Id { get; set; }
public string Name { get; set; } = "unnamed";
public override string ToString() => Id + ":" + Name;
}
class Program
{
// Reference type, implements IHasId, and has a public parameterless constructor.
static T Create<T>(string reason) where T : class, IHasId, new()
{
T fresh = new(); // legal only because of new()
Console.WriteLine("created " + typeof(T).Name + " for " + reason);
return fresh;
}
// Ordering: without IComparable<T> there is no CompareTo to call.
static T Larger<T>(T a, T b) where T : IComparable<T> =>
a.CompareTo(b) >= 0 ? a : b;
// struct means T can never be null, so T? is Nullable<T> and HasValue exists.
static string Show<T>(T? value) where T : struct =>
value.HasValue ? value.Value.ToString()! : "none";
static void Main()
{
Sensor s = Create<Sensor>("the north wall");
s.Id = 3;
s.Name = "north";
Console.WriteLine(s + " id via interface: " + ((IHasId)s).Id);
Console.WriteLine(Larger(41, 42));
Console.WriteLine(Larger("apple", "banana"));
Console.WriteLine(Larger(new DateTime(2024, 1, 1), new DateTime(2023, 12, 31)).ToString("yyyy-MM-dd"));
Console.WriteLine(Show<int>(7) + " " + Show<int>(null));
}
}
Output:
created Sensor for the north wall
3:north id via interface: 3
42
banana
2024-01-01
7 none
One generic method served int, string and DateTime because all three implement IComparable<T> — and a type that does not, such as a plain class of your own, is rejected at the call site with a clear compiler error rather than an InvalidCastException three layers down.
Technical Depth: The Full Menu
Every constraint, and what it buys
| Constraint | Accepts | Unlocks inside the body |
|---|---|---|
where T : class | Reference types | null comparisons, as, reference equality |
where T : struct | Non-nullable value types | T? means Nullable<T>, never null, no boxing |
where T : notnull | Anything not nullable | Safe dictionary keys, nullability warnings that mean something |
where T : new() | Types with a public parameterless constructor | new T() |
where T : SomeBase | That class and its subclasses | Every member of SomeBase |
where T : ISomething | Implementers | Every interface member, without boxing structs |
where T : U | Anything assignable to another parameter | Assignment between the two |
where T : unmanaged | Blittable value types | sizeof, stackalloc, pointer interop |
where T : Enum | Enum types | Typed enum helpers with no boxing |
where T : INumber<T> | Numeric types (.NET 7+) | +, -, *, /, T.Zero, T.One |
Order is enforced, not stylistic: at most one of class/struct/notnull/unmanaged and it comes first, then a base class, then interfaces, then new() last. Several parameters get several clauses, stacked with no commas between them:
class Store<TKey, TItem>
where TKey : notnull
where TItem : class, IKeyed<TKey>, new()
{ }
Why an interface constraint beats a cast
Casting a struct to an interface boxes it — a heap allocation on every call. A constrained type parameter does not: the JIT emits a constrained call that dispatches directly on the value type. So Larger(41, 42) above allocates nothing, while a hand-written Larger(IComparable a, IComparable b) would box both arguments. That single detail is why LINQ, Dictionary<TKey, TValue> and EqualityComparer<T> are built on constraints instead of interface parameters.
The constraints that do not exist
There is no way to demand a constructor with parameters, no way to demand a static member before .NET 7, and no way to say "any of these three unrelated types". The standard workarounds:
// Wanted: where T : new(int). Do this instead.
static T Build<T>(int id, Func<int, T> factory) => factory(id);
// Wanted: an operator constraint on older targets. Pass the operation in.
static T Combine<T>(T a, T b, Func<T, T, T> op) => op(a, b);
Static abstract members changed the arithmetic story
Before .NET 7, "add two values of T" was genuinely unwriteable and every numeric library shipped a hand-rolled workaround. Interfaces can now declare static members, and the numeric hierarchy exposes them:
static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
{
T total = T.Zero; // a static member reached through T
foreach (T v in values) total += v;
return total;
}
INumber<T> sits under INumberBase<T>, IAdditionOperators<,,> and friends, so you can constrain as narrowly as the algorithm needs — IAdditionOperators alone if all you do is add.
The self-referencing constraint
A type parameter may be constrained by a type built from itself, which is how a base class returns the derived type from a fluent method:
abstract class Builder<TSelf> where TSelf : Builder<TSelf>
{
public TSelf WithName(string name) { Name = name; return (TSelf)this; }
public string Name { get; private set; } = "";
}
class SensorBuilder : Builder<SensorBuilder> { }
new SensorBuilder().WithName("north") now returns a SensorBuilder, not a Builder, so chained calls keep the derived members in view. The pattern is worth knowing and worth rationing: it makes signatures noisy fast.
Where constraints are checked, and where they are inherited
Constraints are verified twice at compile time — once against the generic definition's own body, once at every instantiation — and cost nothing at run time. They are inherited: an overriding method may not restate them, because it cannot change them. A generic interface implementation, by contrast, must match the interface's constraints exactly. And where T : notnull produces warnings rather than errors, so it only bites in a project with nullable reference types enabled.
Real World Example: A Keyed Store and Numeric Totals
Two constrained shapes cover a large slice of real code: a dictionary-backed store that insists its keys are safe and its items know their own key, and aggregate maths written once for every numeric type.
using System;
using System.Collections.Generic;
using System.Numerics;
interface IKeyed<TKey> where TKey : notnull
{
TKey Key { get; }
}
record Reading(int Key, double Celsius) : IKeyed<int>;
class Store<TKey, TItem>
where TKey : notnull
where TItem : class, IKeyed<TKey>
{
private readonly Dictionary<TKey, TItem> items = new();
public int Count => items.Count;
public void Put(TItem item) => items[item.Key] = item;
// TItem : class is what makes returning null legal here.
public TItem? Find(TKey key) => items.TryGetValue(key, out TItem? found) ? found : null;
}
static class Stats
{
public static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
{
T total = T.Zero;
foreach (T v in values) total += v;
return total;
}
public static double Average<T>(IReadOnlyList<T> values) where T : INumber<T> =>
values.Count == 0 ? 0 : double.CreateChecked(Sum(values)) / values.Count;
}
class Program
{
static void Main()
{
var store = new Store<int, Reading>();
store.Put(new Reading(1, 20.5));
store.Put(new Reading(2, 22.0));
store.Put(new Reading(1, 21.5)); // same key: replaced, not added
Console.WriteLine("count: " + store.Count);
Console.WriteLine("found: " + store.Find(1));
Console.WriteLine("missing: " + (store.Find(99)?.ToString() ?? "none"));
Console.WriteLine(Stats.Sum(new[] { 1, 2, 3, 4 })); // int
Console.WriteLine(Stats.Sum(new[] { 1.5m, 2.25m })); // decimal
Console.WriteLine(Stats.Average(new[] { 20.5, 22.0, 21.5, 24.0 }));
}
}
Output:
count: 2
found: Reading { Key = 1, Celsius = 21.5 }
missing: none
10
3.75
22
Every line of that output is something a constraint made possible. Store can use item.Key as a dictionary key because IKeyed<TKey> supplies it and notnull promises it is usable as one; it can return null from Find because TItem : class. Stats.Sum added int values and decimal values with one body — T.Zero resolving to 0 and 0m respectively — because INumber<T> exposes the operators as static abstract members.
Notice what is not in the constraints. Store never demanded new(), because it never constructs a TItem; Stats never demanded IComparable<T>, because it never orders anything. Each omission is a caller you did not turn away. When a constraint stops being needed — you deleted the new T() — delete the fine print with it, or you are enforcing a rule nobody benefits from.
Common Mistakes
- Constraining out of habit.
where T : class, new()on a type that never constructs anything and never compares to null blocks every struct and every type without a default constructor, for nothing. - Casting to an interface instead of constraining to it.
((IComparable<T>)a).CompareTo(b)boxes a struct on every call;where T : IComparable<T>does not. - Writing
if (item == null)underwhere T : struct. It can never be true. UseT?andHasValueif absence is a real state. - Assuming
where T : notnullis enforced. It emits a warning, and only with nullable reference types enabled. It documents intent; it does not stop anyone. - Getting the clause order wrong.
where T : new(), classandwhere T : IHasId, SomeBasedo not compile. Primary constraint, then base class, then interfaces, thennew(). - Restating constraints on an override. They are inherited and may not be repeated — that is a compile error, not a style preference.
- Reaching for
where T : Enumand then boxing anyway.Enum.GetValues(typeof(T))throws the type safety away; use the genericEnum.GetValues<T>()andEnum.TryParse<T>overloads. - Faking a parameterised constructor with reflection.
Activator.CreateInstance(typeof(T), args)moves a missing-constructor error to run time. Take aFunc<...>factory and keep it a compile error.
Best Practices
- Start with no constraints and add one only when the body will not compile without it — the loosest fine print that works.
- Prefer an interface constraint to a base-class constraint: it admits structs, admits unrelated hierarchies, and still avoids boxing.
- Use
where TKey : notnullon every dictionary-like key parameter, matchingDictionary<TKey, TValue>itself. - Reach for
where T : structwhen boxing would defeat the purpose, andwhere T : unmanagedonly for interop,stackallocandsizeofwork. - Constrain to the narrowest numeric interface the maths needs —
IAdditionOperatorsfor addition,INumber<T>when you want the whole toolbox. - Take a
Func<T>orFunc<TArg, T>factory rather thannew()plus property assignment when construction needs arguments. - Put each type parameter's clause on its own line once there are two or more; the stacked form is far easier to scan than a single long
where. - Treat the constraint list as public API documentation. Adding one is a breaking change for callers, so decide it deliberately rather than during a refactor.
Practice Exercises
- Write
static T FirstOrCreate<T>(List<T> items) where T : class, new()that returns the first element or a fresh instance, then explain in comments which member of the fine print each half of the body needs. - Write
static T Clamp<T>(T value, T low, T high) where T : IComparable<T>and demonstrate it onint,decimalandDateTimevalues, printing each result. - Write
static T Product<T>(IEnumerable<T> values) where T : INumber<T>usingT.Oneas the seed, and prove it works forint,longanddoublewithout any casts. - Build
class Cache<TKey, TValue> where TKey : notnullwithGetOrAdd(TKey key, Func<TKey, TValue> factory). Then try to addwhere TValue : classand describe exactly which call sites you just broke.