Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# generic method for mathematical operations

Tags:

c#

generics

I would like to create a generic method which performs basic mathematical operations. For eg. If a double is passed to the function, it will return double.

public static T Multiply<T> (T A, int B)
{
   //some calculation here
   return (T) A * B; 
}

This doesn't work for me.

EDIT: I get an error Operator '*' cannot be applied to operands of type 'T' and 'int'

However I am wondering if there are other ways to achieve what I am trying to?

Thanks

like image 626
dopplesoldner Avatar asked Apr 27 '26 04:04

dopplesoldner


1 Answers

You can do it by constructing and compiling a LINQ expression for the specific type, like this:

private static IDictionary<Type,object> MultByType = new Dictionary<Type,object>();
public static T Multiply<T>(T a, int b) {
    Func<T,int,T> mult;
    object tmp;
    if (!MultByType.TryGetValue(typeof (T), out tmp)) {
        var lhs = Expression.Parameter(typeof(T));
        var rhs = Expression.Parameter(typeof(int));
        mult = (Func<T,int,T>) Expression.Lambda(
            Expression.Multiply(lhs, Expression.Convert(rhs, typeof(T)))
        ,   lhs
        ,   rhs
        ).Compile();
        MultByType.Add(typeof(T), mult);
    } else {
        mult = (Func<T,int,T>)tmp;
    }
    return mult(a, b);
}

To avoid recompiling the expression each time it is used, one could cache it in a dictionary.

Note that this approach has certain limitations:

  • Multiplication of T by T is expected to be defined,
  • The output of multiplication is expected to be T without conversion. This is not true for types smaller than int,
  • The type must support conversion from int.

None of this is checked at compile time.

like image 53
Sergey Kalinichenko Avatar answered Apr 28 '26 18:04

Sergey Kalinichenko