lundi 1 mars 2021

C# functions on generic numeric primitives [duplicate]

I routinely want to do generalized functions on "numbers", whether those numbers are ints or doubles or floats or bytes. Just do your arithmetic, adding ints to get ints or duobles to get double, and then return [that]. Unfortunately, C# doesn't seem to have a base "IAddable" interface that all numbers implement. E.g.

public static Val Sum<Val>(this IEnumerable<Val> vals) where Val: IComparable, IFormattable, IConvertible
{
    Val output = default;
    foreach(Val val in vals)
    {
        if(typeof(Val) == typeof(int))
            output = (Val)((int)output + (int)val);
        else if(typeof(Val) == typeof(double))
            output = (Val)((double)output + (double)val);
        else if(typeof(Val) == typeof(byte))
            output = (Val)((byte)output + (byte)val);
        else 
            throw new Exception("Bad type.");
    }
    return output;
}

So, 1) That sucks. I'd rather restrict the function's use than throw an exception when somebody tries Int16 or whatever. 2) It doesn't even compile. "Cannot convert type 'Val' to 'int'."

Is there a "TryCast", like some have "TryParse"? How do I convince C# to just chill and cast what I tell it to cast?





Aucun commentaire:

Enregistrer un commentaire