I have an enumeration and a switch statement based on that enum, which looks like this:
public enum MyEnum
    {
        VAL1,
        VAL2,
        VAL3,
        ONE = 1,
        TWO = 2
    }
and the switch:
switch ((MyEnum)Enum.Parse(typeof(MyEnum), input.ToUpper()))
        {
            case MyEnum.VAL1:
                Console.WriteLine("val1");
                break;
            case MyEnum.VAL2:
                Console.WriteLine("val2");
                break;
            case MyEnum.VAL3:
                Console.WriteLine("val3");
                break;
            case MyEnum.ONE:
                Console.WriteLine("1");
                break;
            default:
                Console.WriteLine("default");
                break;
        }
where input is a string. The problem I have is that I have a compiler error,
The label 'case 1:' already occurs in the switch statement
I found that moving the 'ONE' element as first in the enumeration resolves the issue, but my question is why this happens?
Well because what happens is when you have:
public enum MyEnum
    {
        VAL1,
        VAL2,
        VAL3,
        ONE = 1,
        TWO = 2
    }
You basically have:
public enum MyEnum
    {
        VAL1 = 0,
        VAL2 = 1,
        VAL3 = 2,
        ONE = 1,
        TWO = 2
    }
You see where your problem is, now? You need to assign them different values.
When creating a new enum, its options are actually numbers. If you don't define a specific numeric value to an enum option, the compiler set it by default in an ascending order (0,1,2,...). this is why VAL1=0, VAL2=1 and VAL3=2. then you set a value to ONE=1 and TWO=2 and so you have to different names to the same option (VAL2=ONE=1 and VAL3=TWO=2). a simple console application demonstrates it: example
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