Information Technology Reference
In-Depth Information
Suppose, for example, that you have used the enum declaration for
CardDeckSettings
(given in the preceding code), and have
not
used the
Flags
attribute. The first line of the follow-
ing code creates a variable (named
ops
) of the enum type, and sets the value of a single flag bit.
The second line uses
ToString
to get the string name of the member represented by that value.
CardDeckSettings ops = CardDeckSettings.SingleDeck; // Set the bit flag.
Console.WriteLine( ops.ToString() ); // Print its name.
This code produces the following output:
SingleDeck
Suppose, however, that you set two bit flags instead of one, as in the following code:
// Set two bit flags.
ops = CardDeckSettings.SingleDeck | CardDeckSettings.Animation;
Console.WriteLine( ops.ToString() ); // Print what?
The resulting value of
ops
is 9, where 1 is from the
SingleDeck
flag, and 8 is from the
Animation
flag. In the second line, when
ToString
attempts to look up the value in the list of
enum members, it finds that there is no member with the value 9—so it just returns the string
representing 9. The resulting output is the following:
9
If, however, you use the
Flags
attribute before the declaration of the enum, that tells the
ToString
method that the bits can be considered separately. In looking up the value, it would
find that 9 corresponds to the two bit flag members
SingleDeck
and
Animation
. It would then
return the string containing their names, separated by a comma and space, as shown here:
SingleDeck, Animation