20.10. 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 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, with each value 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 value using Enum.Parse. This method returns an object, which must then be cast to the target enum type in order to use it.
In addition to passing Enum.Parse a single enumeration value as a string, you can also pass the enumeration value as its corresponding numeric value. For example, consider the following line:
Language proj1Language = (Language)Enum.Parse(typeof(Language), "VBNET");
You can ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access