December 21, 2017

C# - Using Enumeration types as bit flags

Enumeration allows you to define named integral constants that could be hold by a variable, which can be used in client code to clearly specify the valid values for a variable, because in Visual Studio, IntelliSense lists the defined values. You may have a scenario where you need to hold combination of more than one values, there comes the bit flags. You can use enum type to define bit flags, which allows the enumeration type to store a combination of the values that are defined in the enum list.

You can create bit flags enum by applying the Flags attribute and defining the values by including a named constant with a value of zero that means "no flags are set.", then define remaining items and set the value of each enumeration item to be a power of 2, this enables you to define the combination of more than one values, for example WeekDaysEnum.Friday | WeekDaysEnum.Monday.

Lets start with following enum of week days.

 [Flags]
 public enum WeekDaysEnum : short
 {
  None = 0, //Use None as the name of the flag constant whose value is zero.
  Friday = 1,
  Saturday = 2,
  Sunday = 4,
  Monday = 8,
  Tuesday = 16,
  Wednesday = 32,
  Thursday = 64
 }

In our client code, we can use this enum as:

 private void Test()
 {
  //Initialize with single value 'Friday'
  WeekDaysEnum visitingDays1 = WeekDaysEnum.Friday;
  
  // assign with two flags using bitwise OR.
  WeekDaysEnum visitingDays2 = WeekDaysEnum.Friday | WeekDaysEnum.Monday;
  // Add more flags using bitwise OR.
  visitingDays2 = visitingDays2 | WeekDaysEnum.Thursday;
  
  // Print visitingDays2 variable, it will give you the output : 
  // Selected days are Friday, Monday, Thursday
  // Note that, it will automatically prepare string of comma separated values.
  Console.WriteLine("Selected days are {0}", visitingDays2);
  
  //Similarly you can remove a flag from variable, using bitwise XOR
  visitingDays2 = visitingDays2 ^ WeekDaysEnum.Thursday;
 }

You can use bitwise AND operator to check whether the variable contains a specific flag/value.

 if ((visitingDays2 & WeekDaysEnum.Friday) == WeekDaysEnum.Friday)
 {
  Console.WriteLine("Friday visit is open.");
 }
 else
 {
  Console.WriteLine("Friday visit is not allowed.");
 }

I hope you find this post helpful. You can find more info about the flags attribute and its usage at: