Advertisement
Intermediate C#, Generics

How do generic type constraints ('where T : ...') restrict what types can be used, and what are the common constraint kinds?

Short answer

Constraints restrict which types are valid for a type parameter, letting you safely use members that constraint guarantees exist — common constraints include 'class' (reference types only), 'struct' (value types only), 'new()' (must have a public parameterless constructor), a…

Save C# mock interview
Advertisement
AModel answer
Constraints restrict which types are valid for a type parameter, letting you safely use members that constraint guarantees exist — common constraints include 'class' (reference types only), 'struct' (value types only), 'new()' (must have a public parameterless constructor), a specific base class/interface, or 'notnull'.
public class Repository<T> where T : class, IEntity, new() {
  public T CreateNew() => new T(); // safe: 'new()' constraint guarantees this works
  public void Validate(T entity) => entity.Validate(); // safe: IEntity constraint guarantees this method exists
}
Real-world example
Constraining a generic repository or factory class to only work with types that are actual entities with an ID and a parameterless constructor.
Likely follow-ups
  • Can you combine MULTIPLE constraints on the same type parameter, and in what order must they appear?
Related topics