
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
22
|
Chapter 1: Numbers and Enumerations
See Also
See the “Enum.ToString Method” and the “Enumeration Format Strings” topics in
the MSDN documentation.
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