Note: This article was originally published in 2011. Some steps, commands, or software versions may have changed. Check the current .Net documentation for the latest information.

Prerequisites

Before you begin, make sure you have:

  • Visual Studio or .NET CLI installed
  • .NET Framework or .NET Core SDK
  • Basic C# programming knowledge

You can simply use the Enum.Parse() function as shown below:

using System;

 enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };

public class Example
{
   public static void Main()
   {
      string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         try {
            Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);
            if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
            else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
         }
         catch (ArgumentException) {
            Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
         }
      }
   }
}
// The example displays the following output:
//       Converted '0' to None.
//       Converted '2' to Green.
//       8 is not an underlying value of the Colors enumeration.
//       'blue' is not a member of the Colors enumeration.
//       Converted 'Blue' to Blue.
//       'Yellow' is not a member of the Colors enumeration.
//       Converted 'Red, Green' to Red, Green.

More details can be found at: (http://msdn.microsoft.com/en-us/library/system.enum.parse.aspx)

Summary

You’ve successfully learned parse an enumeration. If you run into any issues, double-check the prerequisites and ensure your .Net environment is properly configured.