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 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game.
  2. Consulting: If you want to improve feature velocity, reduce costs, and make your systems more scalable, secure, and resilient, then let’s work together and make it happen.
  3. Join my FREE Community on Skool, where you can ask for help, share your success stories and hang out with me and other like-minded people without all the negativity from social media.

 

Leave a Comment

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