What generic constraints does C# support?

C# Type System Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

where T : — class / struct (reference/value type), new() (has a public parameterless constructor), a base class name, one or more interfaces, another type parameter (where T : U), notnull, unmanaged, and class?/default for nullable-annotation nuance. Constraints let the generic code actually use members of T.

The common ones are where T : class or struct to require a reference or value type, where T : new() to require a parameterless constructor so I can create instances, and naming an interface or base class so I can call its members. There's also where T : U relating two type parameters, and newer ones like notnull and unmanaged. The point of all of them is that without a constraint, T is basically object inside the method — a constraint tells the compiler what I'm allowed to do with it.

  • Without a constraint, all you can do to a T is what object allows.
  • where T : IComparable<T> → you can call a.CompareTo(b) inside the method.
  • where T : Entity, new() → create instances and access Entity's members.
  • Multiple constraints: where T : class, IEntity, new() (order matters — class/struct first, new() last).