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

        [Flags]
        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
Advertisement

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

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: