
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Using Enumerated Members in a Bit Mask
|
27
Discussion
If you want to use the HandleFlagsEnum method with existing code, all that is required
is to add an
All member to the existing enumeration. The All member should be
equal to all the members of the enumeration ORed together.
The
HandleFlagsEnum method then uses this All member to determine if an enumera-
tion value is valid. This is accomplished by ANDing the
language value with
Language.All, then verifying that the result equals the original language parameter.
This method can also be overloaded to handle the underlying type of the enumera-
tion as well (in this case, the underlying type of the
Language enumeration is an inte-
ger). The following code determines if an integer variable contains a valid Language
enumeration value:
public static bool HandleFlagsEnum(int language)
{
if ((language != 0) && ((language & (int)Language.All) == language))
{
return (true);
}
else
{
return (false);
}
}
The overloaded HandleFlagsEnum methods return true if the language parameter is
valid and
false otherwise.
See Also
To test for a valid enumeration within an enumeration not marked with the Flags
attribute, see Recipe 1.18.
1.20 Using Enumerated Members in a Bit Mask
Problem
An enumeration of values is needed to act as bit flags that can be ORed together ...