capypad
0 day streak
csharp / expert
Snippet

Generic Math via Static Abstract Members

Static abstract members in interfaces allow C# to define operators and static properties within an interface. This is the foundation of 'Generic Math', enabling developers to write generic algorithms that work across all numeric types (int, float, decimal, etc.) by constraining type parameters to the INumber<T> interface.

snippet.csharp
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Numerics;
 
public static class MathUtils {
public static T SumAll<T>(IEnumerable<T> values) where T : INumber<T> {
T result = T.Zero;
foreach (var value in values) {
result += value;
}
return result;
}
}
 
// Usage
double dSum = MathUtils.SumAll(new[] { 1.5, 2.5 });
int iSum = MathUtils.SumAll(new[] { 10, 20 });
Breakdown
1
where T : INumber<T>
Constrains T to types that implement the standard numeric interface, including operators.
2
T result = T.Zero;
Accesses the static Zero property defined in the interface for the specific type T.
3
result += value;
Uses the static '+' operator defined on the interface to perform addition on generic types.