#193 – An Enum Type’s ToString Method Displays the Member’s Name
December 27, 2010 Leave a comment
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
}