Wednesday, March 9, 2016

C# switch and double assigned enum values

Hi,

today I wanted to trick C#'s switch-case statement, but failed :-)

I tried to create an enum with 2 values pointing to the same value (yes this do is possible).

    public enum TestEnum : uint
    {
      a = 1,
      b = 1,
    }

Main:
    switch (variable)
    {
      case TestEnum.a:
        Console.WriteLine("a");
        break;
      case TestEnum.b:
        Console.WriteLine("b");
        break;
      default:
        break;
    }
... looking at the second part (only) this code makes perfect sense (as a test-case), but in combination it must be considered that the switch-case statement must find a unique case as a target and resolves the values behind the enumeration.

Compiler Error:

Error CS0152: The switch statement contains multiple cases with the label value '1'

... even if i failed to trick the compiler it is good news that c# is consistent here.

Kind regards,
Daniel

No comments: