Using enum types as bit flags in C#

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;

Leave a Comment

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