Reputation: 1075
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?
Upvotes: 4
Views: 700
Reputation: 916
Enumerations in C# are just fancy integers. If you don't explicitly state the value for a enum value the compiler automatically assigns one. So when MyEnum.VAL2
is processed it is assigned the value 1
as it is the second value. Then MyEnum.ONE
comes around and also takes the value 1
as well. In the switch this causes both MyEnum.VAL2
and MyEnum.ONE
to have the value 1
and since a switch may only include a value once, this causes a compiler error. As you already figured out, simply moving the enum values with explicitly stated values to the top solves the issue as the value 1
can then be treated as 'taken'.
Upvotes: 1
Reputation: 234695
VAL2
will have the value 1
(since it is placed just after VAL1
which takes the value 0
). This is the same as the value you've set for ONE
.
The case labels in a switch
have to be different values: that's therefore not true in your case, so compilation fails.
(If you shuffle things around so ONE
and TWO
are at the start, then VAL2
would have the value 4
, and the problem goes away, as you observe).
Upvotes: 1
Reputation: 21
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
Upvotes: 1
Reputation: 413
If I'm not mistaken its because Val2 would be 1 as it's the second enum, and they are zero based, and you have defined another one as "1"(One). So when you move "One" up, it changes the sequence, hence the issue goes away.
Upvotes: 0
Reputation: 2950
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.
Upvotes: 7