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.
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.
Copyright © 2021 Jogjafile Inc.
INumberBase<TSelf>defines severalCreateXoperations which can be used to convert generic value to the target one (and vice versa):INumberBase<TSelf>.CreateChecked<TOther>INumberBase<TSelf>.CreateSaturating<TOther>(TOther)INumberBase<TSelf>.CreateTruncating<TOther>(TOther)Note that based on method and type pair used the result can differ from casting:
So use with caution.
Demo.