#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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #198 – Enumeration Values That Set Combinations of Flags

  1. Naraayanan says:

    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.

  2. 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!

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

%d bloggers like this: