Back to results for “Generics”
C# › Generics

How would you implement generic operator constraints using .NET's generic math interfaces (like INumber<T>) to write a single Sum<T>() method working across int, double, and decimal?

Advanced

Answer

Constrain the generic type parameter to INumber<T> (introduced in .NET 7 alongside static abstract interface members), which guarantees standard arithmetic operators (+, -, etc.) and static members like Zero are available — letting you write ONE generic numeric algorithm that works correctly across every built-in (and custom) numeric type without duplicating overloads for each.
public static T Sum<T>(IEnumerable<T> values) where T : INumber<T> {
  T total = T.Zero;
  foreach (var value in values) total += value;
  return total;
}

int intSum = Sum(new[] { 1, 2, 3 });          // 6
double doubleSum = Sum(new[] { 1.5, 2.5 });    // 4.0
Real-world example Writing a single, reusable Sum(), Average(), or Min()/Max() utility working generically across every numeric type without separate overloads.

Common follow-ups: What is a 'static abstract interface member,' and how does it make this specific generic math pattern possible in C# 11+?