DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 4.2 Converting Plain Text to an Equivalent Enumeration Value

Problem

You have the textual value of an enumeration element, possibly from a database or text file. This textual value needs to be converted to a usable enumeration type.

Solution

The static Parse method on the Enum class allows the textual value of an enumeration element to be converted to a usable enumeration value. For example:

try 
{
    Language proj1Language = (Language)Enum.Parse(typeof(Language), "VBNET");
    Language proj2Language = (Language)Enum.Parse(typeof(Language), "UnDefined"); 
}
catch (ArgumentException e) 
{
    // Handle an invalid text value here (such as the "UnDefined" string)
}

where the following Language enumeration is defined as:

enum Language
{
    Other = 0, CSharp = 1, VBNET = 2, VB6 = 3
}

Discussion

The static Enum.Parse method converts text to a specific enumeration value. This technique is useful when a user is presented a list of values, where each value is defined in an enumeration. When the user selects an item from this list, the text chosen can be easily converted from its string representation to its equivalent enumeration representation using Enum.Parse. This method returns an object of the same type as enumType. This value must then be cast to the same type as enumType in order to use it.

In addition to accepting a single enumeration value as a string, the enumValue parameter can also accept the enumeration value as a corresponding numeric value. For example, the following line:

Language proj1Language = (Language)Enum.Parse(typeof(Language), "VBNET");

could be rewritten as follows to perform the exact same action:

Language proj1Language = (Language)Enum.Parse(typeof(Language), "2");

This is assuming that the Language.VBNET enumeration is equal to 2.

Another interesting feature of the parse method is that it can accept a comma-delimited list of enumeration names or values and then logically OR them together. The following example creates an enumeration with the languages VBNET and CSharp ORed together:

Language proj1Language = (Language)Enum.Parse(typeof(Language), "CSharp, VBNET");

or:

Language proj1Language = (Language)Enum.Parse(typeof(Language), "1, 2");

Each individual element of the comma-delimited list is trimmed of any whitespace, so it does not matter if you add any whitespace between each item in this list.

See Also

See the "Enum.Parse" method in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section