
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Displaying an Enumeration Value as a String
|
21
Discussion
Deriving the textual or numeric representation of an enumeration value is a simple
matter, using the
ToString instance method on the Enum type. This method can
accept a character indicating the type of formatting to place on the enumeration
value. The character can be one of the following: G, g, D, d, X, x, F, or f. See
Table 1-2 for a description of these formatting types.
When printing out the values of an enumeration with the
Flags attribute, the infor-
mation displayed takes into account that more than one of the
enumeration values
may have been ORed together. The output will be all of the enumerations printed
out as strings separated by commas or as the ORed numeric value, depending on the
formatting chosen. For example, consider if the
Flags attribute was added to the
ValidShape enumeration as follows:
[Flags]
enum ValidShape
{
Square = 0, Circle = 1, Cylinder = 2, Octagon = 4
}
Now if you change the code for this recipe as follows:
ValidShape shapeStyle = ValidShape.Circle | 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"));
you will see the ...