I can't figure out how to use switches in combination with an enum. Could you please tell me what I'm doing wrong, and how to fix it? I have to use an enum to make a basic calculator.
public enum Operator
{
PLUS, MINUS, MULTIPLY, DIVIDE
}
public double Calculate(int left, int right, Operator op)
{
int i = (int) op;
switch(i)
{
case 0:
{
return left + right;
}
case 1:
{
return left - right;
}
case 2:
{
return left * right;
}
case 3:
{
return left / right;
}
default:
{
return 0.0;
}
}
}
The end result should be something like this:
Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, PLUS))
Output: The sum of 5 and 5 is 10
Could you guys please tell me how I'm messing up?
You don't need to convert it
switch(op)
{
case Operator.PLUS:
{
// your code
// for plus operator
break;
}
case Operator.MULTIPLY:
{
// your code
// for MULTIPLY operator
break;
}
default: break;
}
By the way, use brackets
Since C# 8.0 introduced a new switch expression for enums you can do it even more elegant:
public double Calculate(int left, int right, Operator op) =>
op switch
{
Operator.PLUS => left + right,
Operator.MINUS => left - right,
Operator.MULTIPLY => left * right,
Operator.DIVIDE => left / right,
_ => 0
}
Ref. https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8
The correct answer is already given, nevertheless here is the better way (than switch):
private Dictionary<Operator, Func<int, int, double>> operators =
new Dictionary<Operator, Func<int, int, double>>
{
{ Operator.PLUS, ( a, b ) => a + b },
{ Operator.MINUS, ( a, b ) => a - b },
{ Operator.MULTIPLY, ( a, b ) => a * b },
{ Operator.DIVIDE ( a, b ) => (double)a / b },
};
public double Calculate( int left, int right, Operator op )
{
return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With