Using the new generic math classes in .NET
Posted: (EET/GMT+2)
With .NET 7 now released (in November 2022), we now have something developers have wanted for a long time: generic math. This means you can write numeric algorithms that work on any numeric type (int, double, decimal, etc.) without repeating your code for all of them. For everyday coding, this opens up some nice possibilities.
.NET 7 introduces a set of new interfaces, like INumber<T>, that give you a common way to express numeric operations. If you have algorithms that previously
required multiple overloads, this can simplify the code considerably.
Here is a tiny example of a generic method that calculates the midpoint between two values, regardless of numeric type:
using System.Numerics;
public static T MidPoint<T>(T a, T b) where T : INumber<T>
{
return (a + b) / T.CreateChecked(2);
}
And you can call it with any supported number type:
int i = MidPoint(10, 20); // int double d = MidPoint(1.5, 3.5); // double decimal m = MidPoint(2m, 4m); // decimal
This used to require multiple overloads or type checking logic. Now it's clean and type safe.
In addition to INumber<T>, there are many other numeric interfaces such as IFloatingPoint<T>, IInteger<T>, and IBinaryInteger<T>. These let you
build algorithms that rely on more specific capabilities when needed.
If you're curious about the full set of interfaces and examples, the .NET docs have a good overview:
Generics in .NET math (Microsoft Docs)
I expect generic math to become one of those features that quietly makes many libraries simpler over time. Even if you don't need it every day, it's great to know it's there.