20.9. Displaying an Enumeration Value as a String
Problem
You need to display the textual or numeric value of an enumeration member
Solution
To display an enumeration value as a string, use the ToString method that each enumeration member inherits from System.Enum.
Using the following ValidShape enumeration type as an example, you can obtain the textual and numeric values so that you can display them:
enum ValidShape
{
Square, Circle, Cylinder, Octagon
}Using the ToString method of the ValidShape enumeration type, you can derive the value of a specific ValidShape enumeration value directly:
Console.WriteLine(ValidShape.Circle.ToString());
Console.WriteLine(ValidShape.Circle.ToString("G"));
Console.WriteLine(ValidShape.Circle.ToString("D"));
Console.WriteLine(ValidShape.Circle.ToString("F"));
Console.WriteLine(ValidShape.Circle.ToString("X"));This generates the following output:
Circle Circle 1 Circle 00000001
If you are working with a variable of type ValidShape, the enumeration values can be derived in the same manner:
ValidShape shapeStyle = ValidShape.Cylinder;
Console.WriteLine(shapeStyle.ToString());
Console.WriteLine(shapeStyle.ToString("G"));
Console.WriteLine(shapeStyle.ToString("D"));
Console.WriteLine(shapeStyle.ToString("F"));
Console.WriteLine(shapeStyle.ToString("X"));The following is displayed:
Cylinder Cylinder 2 Cylinder 00000002
Discussion
Deriving the textual or numeric representation of an enumeration value is a simple matter of using the ToString instance method on ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access