C# and .NET • Modern C# baseline
Generics and Generic Constraints
Reuse algorithms across types while preserving compile-time type safety.
Generics parameterize types and methods without erasing their compile-time contracts. Constraints state what operations a type argument must support. Prefer generic APIs over object-based collections and casts because they catch many mismatches before runtime.
Key points
- Use constraints to document a real requirement.
- Avoid overly broad generic abstractions that make call sites harder to understand.
Example
static T FirstOrDefaultValue<T>(IReadOnlyList<T> values, T fallback)
{
return values.Count == 0 ? fallback : values[0];
}
int result = FirstOrDefaultValue(new[] { 4, 8 }, 0);
Console.WriteLine(result);
What to expect
4
Practice exercise
Add a constraint to a generic method that sorts values and explain which types can be used.
Key idea: Generics preserve the relationship between input and output types.