Home > Mobile >  Is there a better way to instantiate a constant with generic maths?
Is there a better way to instantiate a constant with generic maths?

Time:11-23

I'm experimenting with the new generic math support in .NET 7 and am trying to figure out if there is a better way to express constants that are not 1 or 0. In the function below I am able to construct 9, but it's clearly far from ideal...

public static T DigitalRoot<T>(T value) where T : IBinaryInteger<T> {
    var x = T.Abs(value: value);
    var y = T.Min(x: x, y: T.One);
    var z = (T.One   T.One   T.One   T.One   T.One   T.One   T.One   T.One   T.One);

    return (y   ((x - y) % z));
}

CodePudding user response:

Declare a static readonly field and initialize it with T.CreateChecked(9) as suggested by @MvG. This comes close to a constant:

internal static class BinaryIntegerConstants<T> where T : IBinaryInteger<T>
{
    public static readonly T Nine = T.CreateChecked(value: 9);
}

public static class UncategorizedFunctions
{
    public static T DigitalRoot<T>(T value) where T : IBinaryInteger<T>
    {
        var x = T.Abs(value: value);
        var y = T.Min(x: x, y: T.One);
        var z = BinaryIntegerConstants<T>.Nine;

        return y   ((x - y) % z);
    }
}

Test:

Console.WriteLine(UncategorizedFunctions.DigitalRoot(15));
  • Related