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:

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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.