#197 – Checking an Enumerated Value for the Presence of a Flag

You can combine enum type flags using the bitwise OR operator.  You can also use the bitwise AND operator to check an enumerated value for the presence of a flag.

            Talents fredTalents = Talents.Singing | Talents.Dancing;
            Talents ernieTalents = Talents.Singing | Talents.Juggling | Talents.JokeTelling;

            bool fredCanDance = (fredTalents & Talents.Dancing) == Talents.Dancing;
            bool ernieCanDance = (ernieTalents & Talents.Dancing) == Talents.Dancing;

When a Talents value is bitwise AND’d (&) with a specific flag, e.g. Talents.Dancing, every bit except for the Dancing bit is clear in the value.  The resulting value, of type Talents, is therefore either equal to 0 or to Talents.Dancing.

We could also write the last two lines as:

            bool fredCanDance = (fredTalents & Talents.Dancing) != 0;
            bool ernieCanDance = (ernieTalents & Talents.Dancing) != 0;
Advertisement