Using math functions on numeric types

With .NET 7 the static Math class is no longer required for math functions

Home DailyDrop

Daily Knowledge Drop

.NET 7 introduces the ability to call math methods on numeric types and not have to use the static Math class.


Pre .NET 7

Prior to .NET 7, the static Math class was used:

double value = 100.33;

// get the absolute value
double mathAbs = Math.Abs(value);

// get the cube root
double mathCbrt = Math.Cbrt(125);

.NET 7

In .NET 7, these methods are now available on the numeric type:

double value = 100.33;

double doubleAbs = double.Abs(value);
double doubleCbrt = double.Cbrt(125);

Under the hood, these methods are still using the Math static class:

// source code for the double Abs method
public static double Abs(double value) => Math.Abs(value);

Notes

The two techniques effectively use the same code, and perform the same operation - so which one to use comes down to preference and readability. Personally, I find using the numeric types is more informative, because at a glance one can see the return type of the calculation (the Abs method on double, will return a double) - but this will not be the preference for everyone.


References

Fons Sonnemans Tweet

Daily Drop 187: 21-10-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net .net7 math