.NET 1.1+Convert A String to an Enumeration Value
Enumerations provide an excellent way to name grouped numeric values. Often, the name of an enumeration value will be stored in a database or a file as a string. Later it will need to be converted back to the enumerated type using Enum.Parse.
Enum Class
The Enum class is the base type for all enumerations. It contains a set of methods that can be used to process enumerated types. One of these methods, named Parse, examines the contents of a string and attempts to match it to one of the values from an enumeration. Where a match is found, the value from the enumeration list is returned.
Using Parse
The Parse method is a static member of the Enum class. The method accepts two parameters. The first parameter must contain the type of the enumeration to be compared. The second passes the string being searched for. If the value is matched, the enumeration item is returned as an object that can be cast to the correct type. If the value is not present in the enumeration, an ArgumentException is thrown.
The following example demonstrates the use of Parse using an enumeration and a Main method within a console application.
enum Numbers { Zero, One, Two, Three }
static void Main(string[] args)
{
Numbers num = (Numbers)Enum.Parse(typeof(Numbers), "Two");
Console.WriteLine("{0}={1}", num, (int)num); // Outputs "Two=2"
}
Case Sensitivity
Using this method of parsing a string is case-sensitive. If you need the case of the text to be ignored, add a third Boolean parameter and pass the value true.
26 January 2008