#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
Hi,
Thanks for your information. In this example .you specified 1,2,4,8.Is it compulsory for specifying in enum or Is it takes automatically?and How too use 12,4,8 in the Program.
This is a specialized use of an enumerated type to store flags–true/false values for a series of fields. See https://csharp.2000things.com/2010/12/29/195-using-an-enum-type-to-store-a-set-of-flags/
By default, if you don’t specify explicit values, enumerated type constants take on the values 0,1,2 ..
In your program, you wouldn’t use the actual values, but use the named enumerated constant that makes sense for your application. E.g. Talents myTalent = Talents.Singing;
I’ve been using C# for over 5 years, and this is the first time I’ve ever seen anyone mention the composite value output of the enum’s ToString() method. Excellent information!