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?

3
  • because its using bitwise | operator. if you dont modify values like that it will be like 1 | 3 | 4 | 7 which will result in 7. because 7 is 111 in binary and will eat all the other values ;) Commented Dec 1, 2015 at 20:40
  • Read the answer to the duplicate, especially the "under the covers" section. Commented Dec 1, 2015 at 20:43
  • Thank you everyone, I feel like I understand a lot better now! Commented Dec 1, 2015 at 20:46

1 Answer 1

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 &.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.