#198 – Enumeration Values That Set Combinations of Flags
January 1, 2011 3 Comments
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.
[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.
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.
Console.WriteLine(fred); // SongAndDance Console.WriteLine(sammy); // SongAndDance Console.WriteLine(eddie); // SongAndDance, Juggling Console.WriteLine(bobHope); // DoesItAll