I have to calculate method which takes as parameters the first number, second number and the operation.
public static double Calculate(double firstNumber, double secondNumber, string operation)
{
var result = default(double);
switch (operation)
{
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
result = firstNumber / secondNumber;
break;
}
return result;
}
Right now i am using a switch. When the operation is a "+", i add the numbers.
How could make the calculate method take any arithmetic operator as a parameter without having to add a specific case for it?
My idea would by that in the end it looks like this:
public static string Calculate(double firstNumber, double secondNumber, string operation)
{
return firstNumber operation secondNumber;
}
I know from this question that there is a way, for example using
new DataTable().Compute("1 + 2 * 7", null)
this would require me to convert my numbers to string what i don't want.