
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Testing for a Valid Enumeration of Flags
|
25
protection. Use your own judgment on whether to use the CheckLanguageEnumValue
method to evaluate enumeration values passed in to private methods.
The
HandleEnum method can be called in several different ways. Three of these are
shown here:
HandleEnum(Language.CSharp)
HandleEnum((Language)1)
HandleEnum((Language)someVar) // Where someVar is an int type
Any of these method calls is valid. Unfortunately, the following method calls are also
valid:
HandleEnum((Language)100)
int someVar = 100;
HandleEnum((Language)someVar)
These method calls will also compile without errors, but odd behavior will result if the
code in
HandleEnum tries to use the value passed in to it (in this case the value 100). In
many cases an exception will not even be thrown;
HandleEnum just receives the value
100 as an argument, as if it were a legitimate value of the Language enumeration.
The
CheckLanguageEnumValue method prevents this from happening by screening the
argument for valid
Language enumeration values. The following code shows the mod-
ified body of the
HandleEnum method:
public void HandleEnum(Language language)
{
if (CheckLanguageEnumValue(language))
{
// Use language here...
}
else
{
// Deal with the invalid language value here...
}
}
See Also
To test for a valid enumeration ...