relysis relysis - 3 days ago 6
C# Question

Enumerations with and without values

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?

Answer

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.

Comments