Edit: It seems most people misunderstood my question.
I know how enum works, and I know the binary. I wonder why enumerations with the [Flags] attribute are designed as they are.
Original post:
It may be a duplicate, but I did not find any other posts, so here it goes.
I am sure there was a good justification behind this, I just find it a little error prone.
[Flag] public enum Flagged { One, // 0 Two, // 1 Three, // 2 Four, // 3 } Flagged f; // Defaults to Flagged.One = 0 f = Flagged.Four; (f & Flagged.One) != 0; // Sure.. One defaults to 0 (f & Flagged.Two) != 0; // 3 & 1 == 1 (f & Flagged.Three) != 0; // 3 & 2 == 2
Wouldn't that make sense if he did something like this?
[Flag] public enum Flagged { One = 1 << 0, // 1 Two = 1 << 1, // 2 Three = 1 << 2, // 4 Four = 1 << 3, // 8 } Flagged f; // Defaults to 0 f = Flagged.Four; (f & Flagged.One) != 0; // 8 & 1 == 0 (f & Flagged.Two) != 0; // 8 & 2 == 0 (f & Flagged.Three) != 0; // 8 & 4 == 0 (f & Flagged.Four) != 0; // 8 & 8 == 8
Of course. I'm not quite sure how it should handle user flags like
[Flag] public enum Flagged { One,
The specification gives some recommendations.
Define the enumeration constants by the powers of two, i.e. 1, 2, 4, 8, etc. This means that individual flags in combined enumeration constants do not overlap.
But this should be done automatically, as I bet you will never want my first example to happen. Please enlighten me :)