Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 635
relysis Avatar asked Jan 05 '23 23:01

relysis


2 Answers

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.

like image 147
ThePerplexedOne Avatar answered Jan 12 '23 17:01

ThePerplexedOne


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

like image 36
Mr. Mantis Avatar answered Jan 12 '23 17:01

Mr. Mantis