When you have a plain text that possibly read from a text file or configuration in database for specific enumeration, you can convert this textual value back to its enumeration type. This can be done with the static method Parse on the Enum class.

By using the example RiskLevel as following:

enum RiskLevel
{
    Lowest = 0, Low = 1, Medium = 2, High = 4, Highest = 8
}

And you can get the enumeration type like below:

try
{
    RiskLevel riskLevel = (RiskLevel)Enum.Parse(typeof(RiskLevel), "High");
    RiskLevel riskLevel = (RiskLevel)Enum.Parse(typeof(RiskLevel), "SuperHigh");
}
catch (ArgumentException e)
{
    // handle an invalid text value, like SuperHigh above
}

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:

RiskLevel riskLevel = (RiskLevel)Enum.Parse(typeof(RiskLevel), "High");

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

RiskLevel riskLevel = (RiskLevel)Enum.Parse(typeof(RiskLevel), "4");

This is assuming that the RiskLevel.High enumeration is equal to 4.

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 RiskLevel Low and Medium ORed together:

RiskLevel riskLevel = (RiskLevel)Enum.Parse(typeof(RiskLevel), "Low, Medium");

or:

RiskLevel riskLevel = (RiskLevel)Enum.Parse(typeof(RiskLevel), "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.

Popularity: 2% [?]