#196 – Using the ToString() Method on a Flags-Based Enum Type

When you use the ToString method on an enumeration type that has been defined with the Flags attribute, the method correctly decomposes the current value into its constituent flags.

Assuming the following enumeration type:

        public enum Talents {
            Singing = 1,
            Dancing = 2,
            Juggling = 4,
            JokeTelling = 8};

And the following enumerated values:

            Talents wcFields = Talents.Juggling;
            Talents fredTalents = Talents.Singing | Talents.Dancing;
            Talents ernieTalents = Talents.Singing | Talents.Juggling | Talents.JokeTelling;

The ToString method, implicitly called by Console.WriteLine, produces the following output:

            Console.WriteLine(wcFields);            // Juggling
            Console.WriteLine(fredTalents);         // Singing, Dancing
            Console.WriteLine(ernieTalents);        // Singing, Juggling, JokeTelling