
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
24
|
Chapter 1: Numbers and Enumerations
Suppose you have a method that accepts the Language enumeration, such as the fol-
lowing method:
public void HandleEnum(Language language)
{
// Use language here...
}
You need a method to define the enumeration values you can accept in HandleEnum.
The
CheckLanguageEnumValue method shown here does that:
public static bool CheckLanguageEnumValue(Language language)
{
switch (language)
{
// All valid types for the enum listed here
// This means only the ones we specify are valid.
// Not any enum value for this enum
case Language.CSharp:
case Language.Other:
case Language.VB6:
case Language.VBNET:
break;
default:
Debug.Assert(false, language +
" is not a valid enumeration value to pass.");
return false;
}
return true;
}
Discussion
Although the Enum class contains the static IsDefined method, it should not be used.
IsDefined uses reflection internally, which incurs a performance penalty. Also, ver-
sioning of the enumeration is not handled well. Consider the scenario in which you
add the value
MgdCpp (managed C++) to the Languages enum in the next version of
your software. If
IsDefined is used to check the argument here, it will allow MgdCpp as
a valid value, since it is defined in the enumeration, even though the code for which
you are validating the parameter ...