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

Generic math how to cast from INumber to a "concrete" type (int/double/etc)


Suppose we have a generic method which accepts INumber<T> and returns int:

// process val and return as int
static int DoSomething<T>(T val) where T : INumber<T> => ... 

How can the T be casted to int.


Solution

  • INumberBase<TSelf> defines several CreateX operations which can be used to convert generic value to the target one (and vice versa):

    static int DoSomething<T>(T val) where T : INumber<T> => int.CreateChecked(val);
    

    Note that based on method and type pair used the result can differ from casting:

    var d = double.MaxValue - 1;
    unchecked
    {
        Console.WriteLine((int)d); // -2147483648
        // Console.WriteLine(int.CreateChecked(d)); // throws
    }
    
    Console.WriteLine(int.CreateSaturating(d)); // 2147483647
    Console.WriteLine(int.CreateTruncating(d)); // 2147483647
    

    So use with caution.

    Demo.