Generic Type Constraints
Question
Which
generic type constraintsdo you know?
Short interview answer
Generic constraints restrict the type arguments allowed by a generic declaration and expose the operations that the generic code may safely use. Common constraints include base-class, interface,
class,struct,notnull,unmanaged, andnew()constraints.
Detailed answer
Constraints turn an assumption into a compiler-checked contract. For example, where T : IComparable<T> permits generic code to call CompareTo; where T : new() permits it to construct new T(). A type parameter can have one primary category constraint such as class or a base class, followed by interface constraints, and new() has placement rules. Choose the smallest constraint that expresses what the algorithm truly needs. A constraint is not only validation: it defines the members and operations available inside the generic implementation.