Convert enum values to and from strings in C#

[Convert enum values]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in enums, syntax and tagged , , , , , , , , , , , , . Bookmark the permalink.

3 Responses to Convert enum values to and from strings in C#

  1. Sinan says:

    Can I learn that why all your tutorials built up in earlier version of VS 2012?

    • RodStephens says:

      I use an older version of Visual Studio so people using older versions can easily run the programs. For example, if I used VS 2015, then only those who have that version installed could use it. By using an older version, anyone can run them.

      Honestly there haven’t been all that many earth-shaking additions to Visual Studio for several years anyway, so there isn’t a lot of reason for you to move up to the very latest version anyway.

  2. Sinan Basslan says:

    Completely make sense, that’s why I prefer to have VS 2012 from my starting.
    Thankyou for really good tutorials frequently. I think you are only concern to make tutorials in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *