There's no simple way of doing it with generics, because generics are not templates. You can do it if you supply the operator yourself, like this:
static T binary_apply<T>(T a, T b, Func<T,T,T> add) {
return add(a, b);
}
int a = 4, b = 6;
double x = 2.3, y = 5.2;
Console.WriteLine("Sum of two ints = {0}", binary_apply(a, b, (i,j)=>i+j));
Console.WriteLine("Sum of two doubles = {0}", binary_apply(x, y, (i,j)=>i+j));
Of course this defeats the purpose of having add<T>()
in the first place, because you pass an implementation of the addition as a lambda. You can do this dynamically, too, but that is not the same as having the addition resolved by the compiler:
static T add<T>(T a, T b) {
var p0 = Expression.Parameter(typeof(T));
var p1 = Expression.Parameter(typeof(T));
var ae = Expression.Add(p0, p1);
var f = (Func<T,T,T>)Expression.Lambda(ae, p0, p1).Compile();
return f(a, b);
}
int a = 4, b = 6;
double x = 2.3, y = 5.2;
Console.WriteLine("Sum of two ints = {0}", add(a, b));
Console.WriteLine("Sum of two doubles = {0}", add(x, y));
Demo on ideone.