C# and .NET • Modern C# baseline
Generic Constraints and Reusable Components
Constrain type parameters to the operations your reusable code truly needs.
Constraints can require reference types, value types, interfaces, base classes, or construction capabilities. Constraints improve both documentation and compiler diagnostics. Variance on interfaces and delegates controls safe conversions between related generic types; it is only available for reference-type conversions.
Key points
- Avoid constraints that are stronger than the algorithm requires.
- Covariance supports safe output use; contravariance supports safe input use.
Example
static T Create<T>() where T : new()
{
return new T();
}
var builder = Create<System.Text.StringBuilder>();
Console.WriteLine(builder.Length);
What to expect
0
Practice exercise
Add a constraint that requires IDisposable and describe who owns and disposes the returned object.
Key idea: Use generic constraints to make valid type relationships explicit at compile time.