đź§® One Algorithm, Any Number Type
Sum() works on int, double, decimal? Not before. Generic math lets you write math algorithms once for all numeric types.
❌ Before (Duplicated Code)
int Sum(int[] numbers) {
int total = 0;
foreach (var n in numbers) total += n;
return total;
}
double Sum(double[] numbers) {
double total = 0;
foreach (var n in numbers) total += n;
return total;
}
âś… Generic Math (One Function)
T Sum(T[] numbers) where T : INumber { T total = T.Zero; foreach (var n in numbers) total += n; return total; }
📝 Generic Math Interfaces
// Numeric interfaces (System.Numerics) INumber// Base for all numbers IAdditionOperators // + ISubtractionOperators // - IMultiplyOperators // * IDivisionOperators // / IParsable // T.Parse() ISpanParsable // High-performance parsing // Example: Average function public static T Average (IEnumerable numbers) where T : INumber { T sum = T.Zero; T count = T.Zero; foreach (var n in numbers) { sum += n; count++; } return sum / count; }
âś… Real-World Example
public static T Clamp(T value, T min, T max) where T : INumber { if (value < min) return min; if (value > max) return max; return value; } public static T Lerp (T a, T b, T t) where T : IFloatingPoint { return a + (b - a) * t; } // Works with any numeric type int i = Clamp(5, 0, 10); double d = Clamp(3.14, 0.0, 1.0); decimal m = Lerp(0.0m, 100.0m, 0.5m); // 50.0m
“Wrote 20 overloads for math functions (int, double, float, decimal). Generic math replaced them with 1 generic function. Less code, fewer bugs, works on all numeric types.”
