3

I've come across something which appears strange to me, but at the same time makes some sense for reasons I don't know.

I have this enum:

[Flags] public enum Flags { RemoveQuoteMarks = 1, t1 = 2, t2 = 4, t3 = 8, t4 = 16, t5 = 32, t6 = 64, t7 = 128 }

Before, I didn't manually set the enum values, they index from 0 and standardly increase by 1 right?

Well I noticed odd behavior when I tried to load this string:

string value = "t1, t3, t4, t7";

and parse it using:

Flags flags = (Flags)Enum.Parse(typeof(Flags), value);

and the result was just 't7', so I did some research, and noticed a lot of others used manual indexing where each enum value was doubled by its previous (e.g. 't3 = 8', 't4 = 16'), so I applied this rule to mine, and it worked, my parsed enum had now shown as:

t1, t3, t4, t7

as desired, why do I have to manually configure my enum values like that?

Dean Reynolds
  • 377
  • 2
  • 12

1 Answers1

1

The reason that you need this is that the flags enum is represented as a binary number. Each value that is a power of 2 (1,2,4,8,16 etc.) corresponds to a different index in the binary number:

  • 2 -> 10
  • 4 -> 100
  • 8 -> 1000

This is essential so that you can determine which flags a given value actually contains. For instance if your class has an enum value of 1110 it has the flag values of 2,4 and 8.

If you use values that are not powers of 2, c# can no longer reasonably distinguish which enum values are represented by your classes flags when performing bitwise and &.

James C. Taylor IV
  • 599
  • 10
  • 24