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?
Short answer
Constrain the extension method's generic type parameter to INumber (or a more specific numeric interface like IFloatingPoint ), letting you write ONE generic implementation using standard arithmetic operators that works correctly and efficiently across every built-in (and…
Advertisement
AModel 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.5Real-world example
Writing a single generic Clamp(), Sum(), or Average() utility that works identically across int, double, decimal, and float without duplicated overloads.
Likely follow-ups
- What numeric types beyond the built-in ones can implement INumber<T> to also benefit from generic extension methods like this?
Related topics