
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
20
|
Chapter 1: Numbers and Enumerations
1.16 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 enu-
meration 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")); ...