Friday 26 March 2010

Enum.ToString() Method

Syntax : Enum.ToString(format)

Converts the value of this instance to its equivalent string representation using the specified format.

The format parameter can contain format characters "G" or "g", "D" or "d", "X" or "x", and "F" or "f". If format is a null reference (Nothing in Visual Basic) or an empty string (""), the general format specifier ("G") is used.

Notes to Callers:If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return. For example, the following enumeration defines two members, Shade.Gray and Shade.Grey, that have the same underlying value.

enum Shade
{
White = 0, Gray = 1, Grey = 1, Black = 2
}

The following method call attempts to retrieve the name of a member of the Shade enumeration whose underlying value is 1. The method can return either "Gray" or "Grey", and your code should not make any assumptions about which string will be returned.

string shadeName = ((Shade) 1).ToString("F");

Enumeration Format Strings

You can use the Enum.ToString() method to create a new string object that represents the numeric, hexadecimal, or string value of an enumeration member. This method takes one of the enumeration formatting strings to specify the value that you want returned.

G or g
Enum.ToString("G") : Displays the enumeration entry as a string value, if possible, and otherwise displays the integer value of the current instance.

F or f
Enum.ToString("F") : Displays the enumeration entry as a string value, if possible.

D or d : Displays the enumeration entry as an integer value in the shortest representation possible.

public enum Color {Red = 1, Blue = 2, Green = 3}

Color myColor = Color.Green;

Console.WriteLine("The value of myColor is {0}.", myColor.ToString("G"));
Console.WriteLine("The value of myColor is {0}.", myColor.ToString("F"));
Console.WriteLine("The value of myColor is {0}.", myColor.ToString("D"));
Console.WriteLine("The value of myColor is 0x{0}.", myColor.ToString("X"));
// The example displays the following output to the console:
// The value of myColor is Green.
// The value of myColor is Green.
// The value of myColor is 3.
// The value of myColor is 0x00000003.

No comments:

Post a Comment