#193 – An Enum Type’s ToString Method Displays the Member’s Name

Normally, when you call the ToString method on a variable that stores an integer value, the value of the integer is displayed.

            int x = 42;
            Console.WriteLine(x.ToString());   // Displays: 42
            Console.WriteLine(x);     // Same thing--ToString implicitly called

If you call ToString on an enum type variable, however, the textual name of the enumerated member is displayed.

        public enum Mood {
            Crabby = -5,
            Happy = 5,
            Petulant = -2,
            Elated = 10};

        static void Main()
            Mood myMood = Mood.Crabby;
            Mood dogsMood = Mood.Elated;

            Console.WriteLine(myMood);     // ToString implicitly called; displays: Crabby

            Console.WriteLine(dogsMood);   // Displays: Elated

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: