Advertisement
Intermediate C#, Generics

What are generic constraints and why are they needed?

Short answer

Constraints (where T : ...) restrict the type argument so you can use its members — e.g. class, struct, new(), a base type, or an interface.

Save C# mock interview
Advertisement
AModel answer
Constraints (where T : ...) restrict the type argument so you can use its members — e.g. class, struct, new(), a base type, or an interface.
T Create<T>() where T : new() => new T();
void Sort<T>(List<T> x) where T : IComparable<T> {}
Real-world example
Constraining a repository's entity to a base Entity type so you can read its Id.