[ Team LiB ] |
Recipe 4.1 Displaying an Enumeration Value as a StringProblemYou need to display the textual or numeric value of an enumeration member. SolutionUse the ToString method that each enumeration member inherits from System.Enum. Using the following ValidShape enumeration type as an example, we can obtain the textual and numeric values so that we may display them: enum ValidShape { Square = 0, Circle, Cylinder, Octagon } Using the ToString method of the ValidShape enumeration type, we 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 we 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 DiscussionDeriving 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, F, f, D, d, X, or x. See Table 4-1 for a description of these formatting types.
When printing out the values of an enumeration with the Flags attribute, the information 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 were added to the ValidShape enumeration as follows: [Flags] enum ValidShape { Square = 0, Circle = 1, Cylinder = 2, Octagon = 4 } and if we changed 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")); we would see the following output: Circle, Cylinder Circle, Cylinder 3 Circle, Cylinder 00000003 This technique provides a flexible way of extracting the flags that we are currently using on an enumeration type. See AlsoSee the "Enum.ToString" method and "Enumeration Format Strings" topic in the MSDN documentation. |
[ Team LiB ] |