
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Testing for a Valid Enumeration Value
|
23
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, con-
sider 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.
1.18 Testing for a Valid Enumeration Value
Problem
When you pass a numeric value to a method that accepts an enumeration type, it is
possible to pass a value that does not exist in the enumeration. You want to perform