Flagged Enums
Defining the Flags:
To start of with, declare an enum to list all the possible flags. Two things are important when declaring the enum. The first thing you will probably notice is the [Flags] attribute. This is necessary in order to indicate that the enumeration should be treated as a set of flags. The second important thing is assigning a value to each of the items in the enum. The first value should be 1, then just double the value for each consecutive item. The integer type in .NET can store up to 32 flags.
[Flags] private enum Buttons : int { ···Ok = 1, Cancel = 2, Retry = 4, Help = 8 }
Tip: An “All” item could be added to the list of items in the enumeration as follows: All = Ok | Cancel | Retry | Help
Setting flags ON:
To set multiple flags, concatenate the desired flags using the bitwise OR symbol “|”:
Buttons buttons; buttons = Buttons.Ok | Buttons.Cancel;
Setting flags OFF:
buttons &= ~Buttons.Cancel;
Testing to see if a certain flag is set:
if ((buttons&Buttons.Ok)==Buttons.Ok) Console.WriteLine("Ok");