Enumeration Values That Set Combinations of Flags

When defining a enum type consisting of a set of flags, you normally add values limited to powers of two.  You can also add values that represent combinations of flags.  These can be used as a shortcut for setting several flags using a single value.
Here’s an example where we define several composite values.
1
2
3
4
5
6
7
8
9
10
[Flags]
public enum Talents
{
    Singing = 1,
    Dancing = 2,
    SongAndDance = Singing | Dancing,
    Juggling = 4,
    JokeTelling = 8,
    DoesItAll = SongAndDance | Juggling | JokeTelling
};
Now we can use these composite values when setting flags.
1
2
3
4
Talents fred = Talents.Singing | Talents.Dancing;
Talents sammy = Talents.SongAndDance;           // Same as Fred
Talents eddie = Talents.Singing | Talents.Dancing | Talents.Juggling;
Talents bobHope = Talents.DoesItAll;
The ToString method is also smart enough to list out the composite values, rather than the individual flags.


1
2
3
4
Console.WriteLine(fred);       // SongAndDance
Console.WriteLine(sammy);      // SongAndDance
Console.WriteLine(eddie);      // SongAndDance, Juggling
Console.WriteLine(bobHope);    // DoesItAll