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:

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

The most common way to initialize flags is to use hexadecimal literals.  This is how Microsoft and most C# developers do it:

public enum DaysOfTheWeek
	None = 0,
	Sunday = 0x01,
	Monday = 0x02,
	Tuesday = 0x04,
	Wednesday = 0x08,
	Thursday = 0x10,
	Friday = 0x20,
	Saturday = 0x40,

An even better method might be to use binary literals such as 0b0001, 0b0010, 0b0100, 0b1000, etc., but C# does not provide binary literals.  However, you can simulate a binary literal with the bit shift operator.  This method has the advantage that the numbers visually increase by 1, so it’s very easy to spot errors and see which bit is set for each flag.  Note that this method does not affect program performance because the flag values are calculated at compile time.  This is the method that I use:

public enum DaysOfTheWeek
	None = 0,
	Sunday = 1 << 0,
	Monday = 1 << 1,
	Tuesday = 1 << 2,
	Wednesday = 1 << 3,
	Thursday = 1 << 4,
	Friday = 1 << 5,
	Saturday = 1 << 6,
Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot