Home / Forums / C# 11 Generic Math: Writing Universal Vector Math with INumber<T>

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Source

C# 11 Generic Math: Writing Universal Vector Math with INumber<T>

MathMagician
Vector Math & Physics
MEMBER
Rep: 219
Join Date: Nov 2024
Posts: 8
Thanks: 19
2y ago · Nov 20, 2023 12:45 PM
#1
In older C#, you had to write separate classes for
CODE
Vector3f
(floats),
CODE
Vector3d
(doubles), and
CODE
Vector3i
(integers) because operators (+, -, *, /) could not be used in generic constraints.

C# 11 static abstract interfaces in Generic Math (
CODE
INumber<T>
):


CSHARP
using System.Numerics;

public 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, T scalar) =>
        new(a.X * scalar, a.Y * scalar, a.Z * scalar);

    public T LengthSquared() =>
        (X * X) + (Y * Y) + (Z * Z);

    public T Length() =>
        T.Sqrt(LengthSquared()); // Generic square root!
}


Now a single struct definition works seamlessly with
CODE
float
,
CODE
double
,
CODE
Half
, or
CODE
decimal
with zero boxing overhead!
MathMagician · Vector Math & Physics
Quaternions, transformation matrices, and physics simulation...
The following users thanked MathMagician for this post:
GenericGuru
Templates & Generics
MEMBER
Rep: 154
Join Date: Apr 2023
Posts: 8
Thanks: 35
2y ago · Nov 20, 2023 4:14 PM
#2
Static abstract interface members (
CODE
static abstract T operator +
) was one of the biggest additions in .NET 7. The JIT specializes and inlines the math operations directly into native CPU registers with zero virtual dispatch!
GenericGuru · Templates & Generics
Curiously Recurring Template Pattern (CRTP), C++ concepts, a...
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
2y ago · Nov 21, 2023 12:14 AM
#3
We converted our procedural terrain generator to generic math and could switch between
CODE
float
for real-time rendering and
CODE
double
for 64-bit planetary coordinates without duplicating 2,000 lines of math code.
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...