Using enum types as bit flags in C#

Yan Cui

I help clients go faster for less using serverless technologies.

Usually an enum type is used to define a set of constants such as colours, etc. but you can also use it to define bit flags and stored any combination of the defined values.

You use the FlagsAttribute attribute to create an enum type as bit flags which you can then interact with using the AND (&), OR (|), NOT (~) and XOR (^) bitwise operations:

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

One thing to remember when creating a bit flags is that the default value (0) must be valid (i.e. it must represent one of the defined constants) and it means “the absence of all flags” otherwise the following state will never work:

if ((flag & MyDays.Monday) != 0) // never true if Monday = 0

Here are some examples of the operations which you might want to perform on a bit flags:

// single selection as per normal enum
var today = MyDays.Wednesday;

// making a combination
var mondayOrTuesday = MyDays.Monday | MyDays.Tuesday; // monday or tuesday

// check if an enumeration is part of a combination
var isTodayMondayOrTuesday = ((today & mondayOrTuesday) != 0); // returns false

// finding the overlap between two combinations
var mondayOrWednesday = MyDays.Monday | MyDays.Wednesday;
var overlap = mondayOrTuesday & mondayOrWednesday; // returns MyDays.Monday

// adding an option to an existing combination
var herBirthday = MyDays.Friday;
herBirthday |= MyDays.Thursday;

 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


Leave a Comment

Your email address will not be published. Required fields are marked *