Using enum types as bit flags in C#

Check out my new course Learn you some Lambda best practice for great good! and learn the best practices for performance, cost, security, resilience, observability and scalability.

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:

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;
Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter

Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.

Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. Enrol now and enjoy a special preorder price of £9.99 (~$13).

Start Learning

Are you working with Serverless and looking for expert training to level-up your skills? Or are you looking for a solid foundation to start from? Look no further, register for my Production-Ready Serverless workshop to learn how to build production-grade Serverless applications!

Find a workshop near you