What generic constraints does C# support?
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
Tis whatobjectallows. where T : IComparable<T>→ you can calla.CompareTo(b)inside the method.where T : Entity, new()→ create instances and accessEntity's members.- Multiple constraints:
where T : class, IEntity, new()(order matters —class/structfirst,new()last).