Developer knowledge network · moderated exchange

Zajednica UnreliableCode

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

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Tutorial

C# 11 Generic Math (INumber<T>) for 3D Vector & Matrix Arithmetic [v2.4 Technical Discussion]

dotnet_native_aot
C# Veteran
MEMBER
Rep: 174
Datum pridruživanja: Sep 2021
Postovi: 16
Hvala: 62
prije 1 mjeseci · Jun 28, 2026 12:09 PM
#1

In C# 11, static abstract interface members enable writing generic math classes that work on float, double, and Half simultaneously:

CSHARP
public readonly record struct Vector3<T>(T X, T Y, T Z) where T : INumber<T>, IRootFunctions<T> {
    public static Vector3<T> operator +(Vector3<T> a, Vector3<T> b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
    public static Vector3<T> operator -(Vector3<T> a, Vector3<T> b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
    public T LengthSquared() => X * X + Y * Y + Z * Z;
    public T Length() => T.Sqrt(LengthSquared());
}

One single struct definition handles any numeric precision with JIT monomorphization!

matrix_math_guy
Math Specialist
MEMBER
Rep: 105
Datum pridruživanja: Aug 2018
Postovi: 52
Hvala: 41
prije 1 mjeseci · Jun 28, 2026 2:57 PM
#2

Generic Math in C# is so elegant. Eliminates code duplication between Vector3f and Vector3d.

ptr_arithmetic
C++ Wizard
MEMBER
Rep: 162
Datum pridruživanja: May 2018
Postovi: 73
Hvala: 42
prije 1 mjeseci · Jun 28, 2026 9:37 PM
#3

JIT generates identical machine code to dedicated float structs.