C# generics enable type-safe, reusable code without boxing overhead. Generic constraints (where T : IComparable<T>) let you call methods on T. Covariance (out T) and contravariance (in T) control assignability of generic interfaces. .NET 9 Generic Math (INumber<T>) lets you write arithmetic algorithms once for all numeric types. The "allows ref struct" anti-constraint opens generics to Span<T> and ref structs.
Generic Math with INumber<T>: one method for all numeric types.
List<int> stores ints directly on the heap array — no boxing. Compare with ArrayList which boxes every int to object.
Covariance lets callers pass IReadOnlyList<Derived> where IEnumerable<Base> is expected. Use out T in interface return positions.
Replace Sum(int[]), Sum(double[]), Sum(decimal[]) with a single Sum<T>(T[]) where T : INumber<T>.
Sign in to share your feedback and join the discussion.