2y ago · Nov 20, 2023 12:45 PM
In older C#, you had to write separate classes for (floats), (doubles), and (integers) because operators (+, -, *, /) could not be used in generic constraints.
C# 11 static abstract interfaces in Generic Math ():
Now a single struct definition works seamlessly with, , , or with zero boxing overhead!
CODE
Vector3f CODE
Vector3d CODE
Vector3iC# 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 CODE
decimal
MathMagician · Vector Math & Physics
Quaternions, transformation matrices, and physics simulation...
Quaternions, transformation matrices, and physics simulation...
The following users thanked MathMagician for this post: