#198 – 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.

        [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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers