Title: Convert enum values to and from strings in C#
The System.Enum class provides several methods that convert enum values to and from strings. Some particularly useful methods include:
GetName | Returns the string name of an enum value. |
GetNames | Returns an array of strings holding the names of an enum's values. |
GetValues | Returns an array an enum's values. |
IsDefined | Returns true if a particular value is defined by an enum. |
Parse | Parses a string and returns the corresponding enum value. |
This example uses the following code to demonstrate the GetNames and Parse methods.
// The enumerated type.
private enum MealType
{
Breakfast,
Brunch,
Lunch,
Luncheon = Lunch,
Tiffin = Lunch,
Tea,
Nuncheon = Tea,
Dinner,
Supper
}
// Convert values to and from strings.
private void Form1_Load(object sender, EventArgs e)
{
foreach (string value in Enum.GetNames(typeof(MealType)))
{
// Get the enumeration's value.
MealType meal =
(MealType)Enum.Parse(typeof(MealType), value);
// Display the values.
lstStringValues.Items.Add((int)meal + "\t" + value);
}
}
The code uses Enum.GetNames to get strings representing the MealType values. For each of those strings, it uses Enum.Parse to convert the string into a MealType value. It then displays the value as an integer and in its string form.
Download the example to experiment with it and to see additional details.
|