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
Two things. First, you need to qualify the enum reference in your test - rather than "PLUS", it should be "Operator.PLUS". Second, this code would be a lot more readable if you used the enum member names rather than their integral values in the switch statement. I've updated your code:
public enum Operator
{
PLUS, MINUS, MULTIPLY, DIVIDE
}
public static double Calculate(int left, int right, Operator op)
{
switch (op)
{
default:
case Operator.PLUS:
return left + right;
case Operator.MINUS:
return left - right;
case Operator.MULTIPLY:
return left * right;
case Operator.DIVIDE:
return left / right;
}
}
Call this with:
Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));