Using enum types as bit flags in C#

Usu­al­ly an enum type is used to define a set of con­stants such as colours, etc. but you can also use it to define bit flags and stored any com­bi­na­tion of the defined val­ues.

You use the FlagsAt­tribute attribute to cre­ate an enum type as bit flags which you can then inter­act with using the AND (&), OR (|), NOT (~) and XOR (^) bit­wise oper­a­tions:

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

One thing to remem­ber when cre­at­ing a bit flags is that the default val­ue (0) must be valid (i.e. it must rep­re­sent one of the defined con­stants) and it means “the absence of all flags” oth­er­wise the fol­low­ing state will nev­er work:

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

Here are some exam­ples of the oper­a­tions which you might want to per­form 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 post? Why not support me on Patreon and help me get rid of the ads!