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.
1
2
3
4
5
| 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 Dancingbit 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:
1
2
| bool fredCanDance = (fredTalents & Talents.Dancing) != 0;bool ernieCanDance = (ernieTalents & Talents.Dancing) != 0; |

