Enumerations with and without values

I have an enumeration and a switch statement based on this enum, which looks like this:

public enum MyEnum
    {
        VAL1,
        VAL2,
        VAL3,
        ONE = 1,
        TWO = 2
    }

and 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 with me is that I have a compiler error,

The label "case 1:" already appears in the switch statement

I found that moving the "ONE" element as the first in the enumeration resolves the problem, but my question is: why is this happening?

+4
source share
5 answers

Good, because what happens 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
    }

Now you see where your problem is? You need to assign them different values.

+6
source

VAL2 1 ( VAL1, 0). , , ONE.

case switch : , .

( , ONE TWO , VAL2 4, , ​​ ).

+1

# . , . , MyEnum.VAL2, 1, . MyEnum.ONE , 1. , MyEnum.VAL2 MyEnum.ONE 1, , . , , 1 "".

+1

. enum, (0,1,2,...). VAL1 = 0, VAL2 = 1 VAL3 = 2. ONE = 1 TWO = 2, (VAL2 = ONE = 1 VAL3 = TWO = 2). :

+1

, Val2 1, , , "1" (). , "" , , .

0
source

Source: https://habr.com/ru/post/1662420/


All Articles