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
.
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);
INumberBase<TSelf>.CreateChecked<TOther>
Creates an instance of the current type from a value, throwing an overflow exception for any values that fall outside the representable range of the current type.
INumberBase<TSelf>.CreateSaturating<TOther>(TOther)
Creates an instance of the current type from a value, saturating any values that fall outside the representable range of the current type.
INumberBase<TSelf>.CreateTruncating<TOther>(TOther)
Creates an instance of the current type from a value, truncating any values that fall outside the representable range of the current type.
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.