#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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: #197 – Checking an Enumerated Value for the Presence of a Flag « 2,000 Things You Should Know About C#

  2. Pingback: #198 – Enumeration Values That Set Combinations of Flags « 2,000 Things You Should Know About C#

  3. Pingback: #982 – An Enum Type Can Store a Maximum of 32 Flags | 2,000 Things You Should Know About C#

Leave a comment