#195 – Using an Enum Type to Store a Set of Flags

If you represent a set of boolean values as bits in a larger word, you’ll notice that each flag can be represented by a value that is a power of two.

  • Singing = Bit 0 = 0 0 0 1 = 1
  • Dancing = Bit 1 = 0 0 1 0 = 2
  • Juggling = Bit 2 = 0 1 0 0 = 4
  • Joke-Telling = Bit 3 = 1 0 0 0 = 8

You can use an enum type to represent these flags.

        [Flags]
        public enum Talents {
            Singing = 1,
            Dancing = 2,
            Juggling = 4,
            JokeTelling = 8};

We can use a variable of type Talents to represent either a single talent:

            Talents sinatra = Talents.Singing;    // 1
            Talents wcFields = Talents.Juggling;  // 4

Or we can represent a set of talents using a bitwise OR operator:

            Talents fredTalents = Talents.Singing | Talents.Dancing;    // 1 + 2 = 3
            Talents ernieTalents = Talents.Singing | Talents.Juggling | Talents.JokeTelling;    // 1 + 4 + 8 = 13

The Flags attribute indicates that this enum type can be used to store a set of flags.  Using a different bit for each flag means that we can store any combination of flags at the same time.

Advertisement