Introducing Generic Mathematics in .NET 7 [9]

New in .NET 7 [9]: Generic Mathematics

The latest version of .NET, version 7.0, brings some improvements to generic mathematics. In particular, the base System.Numerics class namespace now includes a few interfaces that allow mathematical operations to be implemented to work on any type of number. This means that calculations can now be performed on integers and fractional numbers of any bit length.

Additionally, some generic math operations marked experimental in .NET 6.0 are now ready for production with .NET 7.0. These operations include INumber, INumberBase, IComparisonOperators, IAdditionOperators, IMultiplyOperators, and ISubtractionOperators. The new number type System.Int128 (integer, 16 bytes) has also been introduced in .NET 7.0.

The following listing shows an example of a generic mathematical calculation in the Calc() method and a generic extraction of a number from a string in ParseNumber(). The Calc() method utilizes the new interface with static abstract members, INumber.

In the Run() method, various calculations are performed using different numeric types, including System.Byte, System.Int32, System.Int128, System.Single, System.Double, System.Decimal, and System.Half. The ParseNumber() method extracts numbers from strings.

The contribution of the C# programming language to this development is the ability to define static abstract members in interfaces. This modifier has been possible experimentally since C# 10.0 and is officially part of the language syntax since C# 11.0. Microsoft uses this modifier in the base classes like INumberBase.

Overall, the improvements to generic mathematics in .NET 7.0 offer greater flexibility and precision for developers working with numerical data.

Leave a Reply