Advanced Generics & Constraints
Prerequisites: Level 2 — Intermediate
A where clause constrains what a generic type parameter must
support — C#'s equivalent of Java's bounded type parameters:
static T Max<T>(T a, T b) where T : IComparable<T> {
return a.CompareTo(b) > 0 ? a : b;
}
static void PrintAll<T>(List<T> items) where T : class {
foreach (T item in items) {
Console.WriteLine(item);
}
}
Common constraints: where T : IComparable<T> (must support
comparison), where T : class (must be a reference type),
where T : new() (must have a parameterless constructor).