Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
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
прадстаўнік: 138
Дата далучэння: Jul 2021
Паведамленні: 10
Дзякуй: 88
1 месяцаў таму · 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
прадстаўнік: 103
Дата далучэння: Apr 2018
Паведамленні: 40
Дзякуй: 24
1 месяцаў таму · 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
прадстаўнік: 151
Дата далучэння: May 2020
Паведамленні: 8
Дзякуй: 36
1 месяцаў таму · Jul 15, 2026 9:03 PM
#3

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