If you want an alternative solution that's more straightforward but involves a tiny bit more redundancy, you can try something I just whipped up. An advantage here is that it's fully typesafe.
Here's a quick a dirty version that implements + and - operations for int and float. It should be trivial to extend it to include more operations as well as support more primitive types (double, decimal, etc) -or even custom types for that matter. Just replace GenericMath with whatever you need.
class Program
{
static void Main(string[] args)
{
var gsInt = new GenericMath<int,IntOperators>();
var gsFloat = new GenericMath<float,FloatOperators>();
var intX = gsInt.Sum( 2, 3 );
var floatX = gsFloat.Sum( 2.4f, 3.11f );
}
}
interface IOperators<T>
{
T Sum( T a, T b );
T Difference( T a, T b );
}
sealed class IntOperators : IOperators<int>
{
public int Sum( int a, int b ) { return a + b; }
public int Difference( int a, int b ) { return a - b; }
}
sealed class FloatOperators : IOperators<float>
{
public float Sum( float a, float b ) { return a + b; }
public float Difference( float a, float b ) { return a + b; }
}
class GenericMath<T,Y>
where Y : IOperators<T>, new()
{
private readonly static Y Ops = new Y();
public T Sum( T a, T b )
{
return Ops.Sum( a, b );
}
public T Difference( T a, T b )
{
return Ops.Difference( a, b );
}
}