Back to results for “Generics”
C# › Extension Methods

How would you write generic extension methods leveraging C# 11's generic math interfaces (like INumber<T>) to build a single reusable numeric utility working across int, double, decimal, and other numeric types?

Advanced

Answer

Constrain the extension method's generic type parameter to INumber<T> (or a more specific numeric interface like IFloatingPoint<T>), letting you write ONE generic implementation using standard arithmetic operators that works correctly and efficiently across every built-in (and custom) numeric type implementing that interface, without needing separate overloads for each numeric type.
public static class NumericExtensions {
  public static T Clamp<T>(this T value, T min, T max) where T : INumber<T> =>
    value < min ? min : (value > max ? max : value);
}

int clampedInt = 15.Clamp(0, 10);       // 10
double clampedDouble = 2.5.Clamp(0.0, 5.0); // 2.5
Real-world example Writing a single generic Clamp(), Sum(), or Average() utility that works identically across int, double, decimal, and float without duplicated overloads.

Common follow-ups: What numeric types beyond the built-in ones can implement INumber<T> to also benefit from generic extension methods like this?