Home > .net, c# > Flagged Enums

Flagged Enums

January 27th, 2009 fbis

[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");
Categories: .net, c# Tags:
Comments are closed.