1

I have an enum type with some discontinued values for each enum. When I try to cast an int value to the enum type it returns with multiple enum values seperated with the | operator. Can anyone explain this logic of how it is cast?

enum EnumTest
{
    Test1 = 0,
    Test2 = 1,
    Test3 = 1 << 1,
    Test4 = 1 << 2,
    Test5 = 1 << 12,
    Test6 = 1 << 13,
    Test7 = 1 << 20,
    Test8 = 1 << 22,
    Test9 = 1 << 23,
    Test10 = 1 << 24,
    Test11 = 1 << 25,
    Test12 = 1 << 14,
    Test13 = 1 << 15,
    Test14 = 1 << 16,
    Test15 = 1 << 25,
    Test16 = 1 << 17,
    Test17 = 1 << 18,
    Test18 = 1 << 19,
    Test19 = 1 << 21,
    Test20 = 1 << 26
}

public void method1()
{
    int number=67239937;
    EnumTest e = (EnumTest)number; //output: Test2|Test16|Test20
}
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
sarath kumar
  • 209
  • 5
  • 12
  • 1
    The question isn't a direct dupe but the current accepted answer covers your question. – TheLethalCoder May 10 '17 at 09:54
  • 1
    Also related: http://stackoverflow.com/questions/29482/cast-int-to-enum-in-c-sharp?rq=1 – TheLethalCoder May 10 '17 at 09:55
  • The "logic" involved in the cast, incidentally, is really simple -- there is no logic. `e` has the value `67239937` under the covers. The actual mapping to the enum tags is of no concern to the compiler -- enums are really just dolled up integers. It's when the value is interpreted by other pieces of code that the tags come into play. – Jeroen Mostert May 10 '17 at 09:57

1 Answers1

3

Let's say your enum is this:

enum E {
    A = 1
    B = 2
    C = 4
    D = 8
}

If you translate each value to it's binary value, you get:

A = 0001
B = 0010
C = 0100
D = 1000

Now let's say you try to convert 12, 1100 in binary, to this enum:

E enumTest = (E)12;

It will output C|D

| being the OR operator, C|D would mean 0100 OR 1000, which gives us 1100, or 12 in decimal.

In your case, it's just trying to find which enum combination is equal to 67239937. This is converted to binary as 100000000100000000000000001. This then converts to Test2|Test16|Test20 or 1|(1 << 17)|(1 << 26).

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69