I have a friend who is just starting to learn C#, so I am getting some interesting questions whose answers seem obvious to me but apparently not to beginners.  Today I answer the question: What’s the best way to initialize Flags enumerations in C#?

As a quick review, here is how Microsoft describes the Flags enumeration:  “You can use an enumeration type to define bit flags, which enables an instance of the enumeration type to store any combination of the values that are defined in the enumerator list.  (Of course, some combinations may not be meaningful or allowed in your program code.)  You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them.”

In other words, each enumeration value must correspond to a single, unique bit.  So one way to initialize flags is to use integers that are a power of 2.  The disadvantage of this method is it’s not easy to see which bit is being set, and errors might creep in enumerations with many flags, especially when you start getting up into the range of 16384, 32768, 65536, and 131072.  But there is nothing inherently wrong with this approach either:

[Flags]
public enum DaysOfTheWeek
{
	None = 0,
	Sunday = 1,
	Monday = 2,
	Tuesday = 4,
	Wednesday = 8,
	Thursday = 16,
	Friday = 32,
	Saturday = 64,
}

Read the rest of this entry »