Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Discussion

C# 11 Generic Math (INumber<T>): Writing Universal Numeric Algorithms with Static Abstract Interface Members [StackOverflow Architecture Guide]

generic_math_geek
C# 11 Math Guru
MEMBER
Rep: 138
Datum pridruživanja: Jul 2021
Postovi: 10
Hvala: 88
prije 1 mjeseci · Jul 15, 2026 4:35 AM
#1

How C# 11 static abstract members in interfaces enable universal numeric algorithms:

CSHARP
public static T SumArray<T>(ReadOnlySpan<T> numbers) where T : INumber<T>
{
    T total = T.Zero;
    foreach (T n in numbers)
        total += n;
    return total;
}

// Works on int, float, double, decimal, Half, BigInteger, and custom types!
int sumInt = SumArray<int>([1, 2, 3, 4]);
double sumDouble = SumArray<double>([1.5, 2.5, 3.5]);

The JIT compiler monomorphizes generic math calls into native CPU assembly with zero boxing and zero interface dispatch overhead!

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rep: 103
Datum pridruživanja: Apr 2018
Postovi: 40
Hvala: 24
prije 1 mjeseci · Jul 15, 2026 7:18 AM
#2

Static abstract interface members (INumber<T>, IFloatingPoint<T>) solved a 20-year limitation in C# where generic operators like + and * were impossible.

simd_vector_ace
SIMD & Intrinsics
MEMBER
Rep: 151
Datum pridruživanja: May 2020
Postovi: 8
Hvala: 36
prije 1 mjeseci · Jul 15, 2026 9:03 PM
#3

Clean, type-safe, and generates identical machine code to hand-written scalar arithmetic.