I have not used generics much and so cannot figure out if it is possible to turn the following three methods into one using generics to reduce duplication. Actually my code currently has six methods but if you can solve it for the three then the rest should just work anyway with the same solution.
private object EvaluateUInt64(UInt64 x, UInt64 y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateFloat(float x, float y)
{
switch(Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
private object EvaluateDouble(double x, double y)
{
switch (Operation)
{
case BinaryOp.Add:
return x + y;
case BinaryOp.Subtract:
return x - y;
case BinaryOp.Multiply:
return x * y;
case BinaryOp.Divide:
return x / y;
case BinaryOp.Remainder:
return x % y;
default:
throw new ApplicationException("error");
}
}
I am building a simple expression parser that then needs to evaluate the simple binary operations such as addition/subtraction etc. I use the above methods to get the actual maths performed using the relevant types. But there has got to be a better answer!