Search code examples
c#generics.net-7.0c#-11.0.net-generic-math

Using Numeric literals/constants in Generic Math C# 11


I am working with the new Generic Math System in C# 11, which is cool, but I haven't found a way to use numeric literals or mathematical constants with them.

The following example which calculates the circumference of a circle does not work.

public T Circumference<T>(T radius) where T : INumber<T>
{
    return 2 * Math.PI * radius;
}

The int (2) and double (Math.PI) cannot be converted to T. This also doesn't work when using the IFloatingPoint interface instead of INumber.

Is there any way to use constants and literals in conjunction with Math Generics?


Solution

  • I would recommend to use IFloatingPoint<TSelf> interface which has defined constants like π:

    public T Circumference<T>(T radius) where T : IFloatingPoint<T>
    {
        return T.CreateChecked(2) * T.Pi * radius;
    }
    

    As for conversion you can use INumberBase<T>.ConvertX methods (see this and this answers, was going to close the question as duplicate using those, but considered information about π worth a separate answer)

    Note that if you still will want to use numbers which are not floating point ones then you possibly will want to convert to double first (Math.PI) and then to T but either way you will end up with precision loss.