Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to turn these 3 methods into one using C# generics?
    text
    copied!<p>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.</p> <pre><code> 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"); } } </code></pre> <p>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!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload