Recipe1.17.Converting Plain Text to an Equivalent Enumeration Value


Recipe 1.17. 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 rewrite this as follows to perform the exact same action:

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

This is assuming that the Language.VBNET enumeration value 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"); 

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" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net