Given the following flags,
[Flags]
public enum Operations
{
add = 1,
subtract = 2,
multiply = 4,
divide = 8,
eval = 16,
}
How could I implement an IF condition to perform each operation? In my attempt, the first condition is true for add, eval, which is correct. However the first condition is also true for subtract, eval, which is incorrect.
public double Evaluate(double input)
{
if ((operation & (Operations.add & Operations.eval)) == (Operations.add & Operations.eval))
currentResult += input;
else if ((operation & (Operations.subtract & Operations.eval)) == (Operations.subtract & Operations.eval))
currentResult -= input;
else
currentResult = input;
operation = null;
return currentResult;
}
I cannot see what the problem is.
Change your inner
&to|:This is equivalent to:
which might be more readable. You might also want to consider an Extension like this:
then you can do this:
which might be even more readable. Finally you could create this extension for even more fun:
Then your expression could turn into: