I want to make the following class to work with int
, double
and other additive types without run-time overhead on boxing/unboxing, but with possibility to reuse from another generic type:
public class agg<T>{
public static T add(T a,T b){return a+b;} // compile error: Operator '+' cannot be applied to operands of type 'T' and 'T'
public static T add(T a,T b){return (dynamic)a+b;} // compiles, but involves boxing and unboxing at run-time
}
How can I achieve that ?
If I define method for each type explicitly, I can't use that class from another generic type test<T>
without defining methods for each type explicitly in that class too:
public class agg<T>{
//public static T add(T a,T b){return a+b;} // compile error: Operator '+' cannot be applied to operands of type 'T' and 'T'
//public static T add(T a,T b){return (dynamic)a+b;} // compiles, but involves boxing and unboxing at run-time
public static int add(int a,int b){return a+b;} // won't be matched by test agg<T>.add(a,b) invokation
}
public class test<T>{
public test(T a,T b){
var c=agg<T>.add(a,b); //compile error: The best overloaded method match for 'agg<T>.add(int, int)' has some invalid arguments
}
}