20.13. Using Enumerated Members in a Bit Mask
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]
public enum RecycleItems
{
None = 0x00,
Glass = 0x01,
AluminumCans = 0x02,
MixedPaper = 0x04,
Newspaper = 0x08
}Combining elements of this enumeration is a simple matter of using the bitwise OR operator (|). For example:
RecycleItems items = RecycleItems.Glass | RecycleItems.Newspaper;
Discussion
Adding the Flags attribute to an enumeration marks this enumeration as individual bit flags that can 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 attribute will not generate an exception or a compile time error, even if the enumeration values are used as bit flags.
The addition of the Flags attribute provides you with two 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access