0

I have this enum:

[Flags]
public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 2 ^ 1,
    Value2 = 2 ^ 2,
    Value3 = 2 ^ 3,
    Value4 = 2 ^ 4
}

Now I want to use a switch on this enum:

public void SwitchThroughEnum(MyEnum myEnum)
{
    switch (myEnum)
    {
        case MyEnum.NegativeValue:
            break;
        case MyEnum.Value0:
            break;
        case MyEnum.Value1:
            break;
        case MyEnum.Value2:
            break;
        case MyEnum.Value3:
            break;
        case MyEnum.Value4:
            break;
        default:
            break;
    }
}

But I can't compile this, because Visual Studio tells me that "The switch statement contains multiple cases with the label value '0'". I don't know why it does that.

enter image description here

EDIT: Is there any possibility to create the enum in a way to just use the power of 1, 2 etc? I sometimes have enums with way more then 30 entries, and calculating and writing the numbers is time killing

DudeWhoWantsToLearn
  • 751
  • 2
  • 10
  • 29

3 Answers3

4

You are using the Logical exclusive OR operator ^ not raising a number to a power.

C# doesn't have a power operator, and you can't use Math.Pow as it's not a constant and well, it returns a double.

Maybe you want binary literals instead:

public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 0b0000001,
    Value2 = 0b0000010,
    Value3 = 0b0000100,
    Value4 = 0b0001000,
}

Or

public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 1,
    Value2 = 2,
    Value3 = 4,
    Value4 = 8,
}
halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
4

I sometimes have enums with way more then 30 entries, and calculating and writing the numbers is time killing

Yeah, just bit shift.

[Flags]
public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 1,
    Value2 = 2 << 0,
    Value3 = 2 << 1,
    Value4 = 2 << 2
}
Zer0
  • 7,191
  • 1
  • 20
  • 34
2

This is the boolean XOR operator Microsoft docs

Exclusive or or exclusive disjunction is a logical operation that outputs true only when inputs differ (one is true, the other is false)

So the 2 ^ 2 is indeed 0

The ^ operator computes the bitwise logical exclusive OR, also known as the bitwise logical XOR, of its integral operands.

So in bit logic 10 XOR 10 = 0

My guess is that you want to use the power of 2 on 2, so why don't you do it directly?

[Flags]
public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 2,
    Value2 = 4,
    Value3 = 8,
    Value4 = 16
}
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61