4.5. Using Enumerated Members in a Bitmask
Problem
An
enumeration of values is needed to act as bit flags that can be
ORed together to create a combination of values
(flags) in the enumeration.
Solution
Mark the enumeration with the
Flags attribute:
[Flags]
enum Language
{
CSharp = 0x0001, VBNET = 0x0002, VB6 = 0x0004, Cpp = 0x0008
}Combining elements of this enumeration is a simple matter of using
the bitwise OR operator (|).
For example:
Language lang = Language.CSharp | Language.VBNET;
Discussion
Adding the Flags attribute to an enumeration marks
this enumeration as individual bit flags that can potentially be
ORed together. Using an enumeration of flags is no
different than using a regular enumeration type. It should be noted
that failing to mark an enumeration with the Flags
would not generate an exception or a compile-time error even if the
enumeration were used as bit flags.
The addition of the Flags attribute provides you
with three benefits. First, if the Flags attribute
is placed on an enumeration, the
ToString and
ToString("G") methods return a string consisting
of the name of the constant(s) separated by commas. Otherwise, these
two methods return the numeric representation of the enumeration
value. Note that the ToString("F") method returns
a string consisting of the name of the constant(s) separated by
commas, regardless of whether this enumeration is marked with the
Flags attribute. For an indication of why this
works in this manner, see the "F" formatting type in ...