1

I was using the switch statement in C# and I realised, though the variable passed in the switch statement is an enum, the switch statement does not throw an error for case 0, but does throw an error for case 1,2,3... I was wondering why is it so. I know how to use enums with the switch case and I don't need help with that, I want to know why isn't it throwing an error with 0. Since 0 is an integer.

Here is the code, and this compiles without any errors. MathOperator is an enum.

 public double Test5(double num1, double num2, MathOperator op)
    {
        double answer=0;
        switch (op)
        {

            case 0:
                {
                    break;
                }

        }
        return answer;
    }

Thank you for answering my question!

  • 1
    instead of using 0,1,2,3,..., try to use the enum name in your case – lamandy Nov 29 '17 at 02:10
  • 1
    You should include the error and the declaration of `MathOperator` since they are both clearly relevant. And what @lamandy said :) – zzxyz Nov 29 '17 at 02:12

2 Answers2

2

There is a rule in the C# specification chapter 13 "Conversions":

13.1.3 Implicit enumeration conversions
An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type.

So 0 is special here in a way that no other integer literal is.

harold
  • 61,398
  • 6
  • 86
  • 164
0

Try this. You need a default case to handle all other MathOperator that is passed into the method Test5 that is currently not in your switch statement, which I think is the issue in your case. A rule of thumb would be to have a switch case that checks against all enum members listed in your enum.

 public double Test5(double num1, double num2, MathOperator op)
 {
    double answer=0;
    switch (op)
    {
        // Use it like this.
        case MathOperator.YourOperator:
        {
            break;
        }
        case MathOperator.Multiply:
        {
            break;
        }
        default:
        {
            // Other cases
        }
    }
    return answer;
}
IvanJazz
  • 763
  • 1
  • 7
  • 19
  • Doesn't really answer the question as to why `0` is allowed, but the others aren't. Can't find the part of the spec that explains that at the moment, but `0` is a special case. – Kirk Woll Nov 29 '17 at 02:14
  • @KirkWoll Thanks for pointing that out, updated. – IvanJazz Nov 29 '17 at 02:20