Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 182 ยท Generics

Generic Constraints

Learn C# generic constraints: class, struct, new(), notnull, unmanaged, base classes, interfaces, combining them, allows ref struct, and good design.

A bare T in a generic type is a stranger: the compiler knows nothing about it except that it is some type, so you can store it, pass it around and compare it to default, but you cannot compare it with <, call a method on it or create one with new. A constraint is a promise the caller must keep, written with where, that tells the compiler more about T. In return, you get to use those abilities inside the generic code.

Constraints are checked at compile time at the call site, so a wrong type argument is rejected before the program runs. This lesson goes through every kind of constraint, how to combine them, the newest one (allows ref struct), and how to decide which constraints a generic API should have.

The problem: what can you do with T?

Let's try to write a generic Max without any constraint:

C# Comparing unconstrained T (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler refuses with error CS0019: Operator '>' cannot be applied to operands of type 'T' and 'T'. It cannot know that every possible T supports >. We have to say what kind of T is allowed.

Interface constraints

The most common constraint says "T must implement this interface". IComparable<T> promises a CompareTo method, so we can compare:

C# where T : IComparable of T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

int, string, double and DateTime all implement IComparable<T> for themselves, so all four calls compile. A type that doesn't implement it is rejected where you call, not inside Max:

C# A type that breaks the promise (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The error is error CS0311: The type 'Point' cannot be used as type parameter 'T' in the generic type or method 'Max<T>(T, T)'. There is no implicit reference conversion from 'Point' to 'System.IComparable<Point>'. That message is the constraint doing its job: tell the caller which promise was broken.

Base class constraints

You can require T to be a particular class or a subclass of it. Inside the method you can use everything the base class offers:

C# where T : Animal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You may ask why not simply write Describe(Animal animal). For Describe you could. The generic version pays off when the method returns the same type it received: Louder(dog, otherDog) returns a Dog, not just an Animal, so the caller needs no cast. With one constrained T you keep the specific type.

class, struct, class?, notnull

Four constraints restrict the kind of type:

Constraint Means
where T : class A reference type (non-nullable when nullable annotations are on)
where T : class? A reference type, nullable or not
where T : struct A non-nullable value type, such as int or a struct (but not int?)
where T : notnull Any non-nullable type, reference or value

Why would you want these? class lets you compare with null meaningfully and store null; struct guarantees the value can't be null and lets you use T? to mean Nullable<T>:

C# class and struct constraints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

notnull is what Dictionary<TKey, TValue> uses for TKey, because a dictionary key can never be null. With nullable reference types on, passing a string? there makes the compiler warn.

The new() constraint

where T : new() promises a public parameterless constructor, so the generic code can write new T():

C# where T : new()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

List<int> and Widget both have public parameterless constructors, so they qualify; Fill<string> would be rejected with error CS0310: 'string' must be a non-abstract type with a public parameterless constructor, because string has none. Notice the rule for combining: new() must be last in the constraint list. Behind the scenes new T() uses reflection-like machinery (Activator.CreateInstance<T>()), so it's slower than a direct new Widget(). If you need a factory with parameters, accept a Func<T> instead.

unmanaged and Enum constraints

where T : unmanaged means T is a value type that contains no references at all (all fields are, recursively, numbers, bool, char, enums, pointers or other unmanaged structs). This is how you write code that reinterprets memory, uses sizeof(T) or stackalloc safely:

C# where T : unmanaged

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two more special base-type constraints exist: where T : Enum (any enumeration) and where T : Delegate (any delegate type). They let you write helpers over all enums:

C# where T : struct, Enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Enum.GetValues<T>() and Enum.TryParse<T> are themselves written with where T : struct. Adding Enum as well is what lets your own helper reject int and other non-enum structs.

Combining constraints

A type parameter can have several constraints, in this order: the primary one first (class, struct, notnull, unmanaged, or a base class), then interfaces, then new() last. Each type parameter gets its own where clause:

C# Several constraints and several type parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Constraints are part of the contract of your type. If Registry were also required to accept structs, class would have to go. Choosing constraints is design work; see the guidelines below.

allows ref struct (C# 13)

Before C# 13, a type argument could never be a ref struct such as Span<T> or ReadOnlySpan<char>, because ref structs may only live on the stack and generic code might box or store them. That blocked generic helpers from working with spans. C# 13 / .NET 9 added an anti-constraint: where T : allows ref struct says "this generic code is written so that T may be a ref struct". The compiler then applies ref-struct rules (no boxing, no storing in fields of normal classes, no capturing in lambdas) inside the method:

C# allows ref struct (C# 13)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The library uses this itself: in .NET 9 and later, Func<T>-like delegates and interfaces gained allows ref struct on some parameters, so you can pass spans to generic APIs. You will meet it rarely in application code; just recognise it when you read modern library signatures.

Designing constraints well

  • Constrain to what you use, nothing more. Each extra constraint shrinks the set of callers. If you only compare for equality, IEquatable<T> is enough (or no constraint at all, using EqualityComparer<T>.Default).
  • Prefer interfaces to base classes. Value types and unrelated classes can implement an interface; only one class hierarchy can satisfy a base-class constraint.
  • Prefer passing a delegate to demanding a constructor. Func<T> factory is more flexible than new(): it supports constructor arguments, pooling and caching.
  • Don't constrain to a sealed class. where T : string is a compile error (CS0701) because only one type could ever match; just use string.
  • Constraints don't inherit by magic. If class A<T> where T : IComparable<T> is used inside class B<T>, B<T> must repeat (or imply) the same constraint.
  • Remember the nullable side of things. With nullable reference types on, where T : class excludes string? and the T? shape needs thought; use class? or notnull deliberately.

Remember generic math, where interface constraints such as INumber<T> bring operators like + to generic code, the modern answer to the a > b problem at the top of this lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the compiler report an error if you call Max<Point>(a, b) and Max has where T : IComparable<T> but Point does not implement it?

    Constraints are checked at compile time where the generic is used, so the caller sees error CS0311 and Max itself is compiled once.
  2. 2. Which line is a valid constraint list?

    The primary constraint (class, struct, base class) comes first, interfaces next and new() must be last. class and struct can't be combined.
  3. 3. What does where T : struct allow you to write that class does not?

    With struct, T is a non-nullable value type, so T? means Nullable<T>. A class constraint is the one that makes null comparisons meaningful.
  4. 4. Why is where T : IComparable<T> usually better than where T : SomeBaseClass for a general helper?

    An interface constraint accepts any type that opts in, including structs such as int. A base-class constraint accepts only subclasses of that one class.
  5. 5. What does where T : allows ref struct (C# 13) do?

    It is an anti-constraint: it widens the set of allowed type arguments to include ref structs, and the compiler then enforces that the code does not box or store T in unsafe ways.

Summary

  • A constraint (where T : ...) promises something about T, letting generic code use operators, methods or new T() it otherwise could not.
  • Kinds: interface, base class, class/class?, struct, notnull, unmanaged, new(), Enum, Delegate, and allows ref struct (C# 13).
  • Multiple constraints on one parameter go primary first, interfaces next and new() last; each type parameter gets its own where clause.
  • Violations are compile errors at the call site (for example CS0311).
  • Constrain only what you need, prefer interfaces, and prefer a Func<T> over new() when you need flexibility.

Next: Generic Methods and Delegates