Convert enum values to and from strings in C#

The System.Enum class provides several methods for converting values between strings and enumerated types. Some particularly useful methods include:

GetNameReturns the string name of an enum value.
GetNamesReturns an array of strings holding the names of an enum's values.
GetValuesReturns an array an enum's values.
IsDefinedReturns true if a particular value is defined by an enum.
ParseParses 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 example


-->