#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

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

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

  1. DominikPalo says:

    Or you can simply use the Enum.HasFlag(Enum flag) method to determine the presence of flag

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: