Flagged Enums

[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)

Using generics

You can check for individual flags being set with the following generic function.

/// <summary>
/// See if a flagged enum is set
/// </summary>
/// <typeparam name="T">enum to check</typeparam>
/// <param name="input">enum instance to check</param>
/// <param name="match">flag to check for</param>
/// <returns>true if its set</returns>
public static bool IsSet<T>(this T input, T match)
	return (Convert.ToUInt32(input) & Convert.ToUInt32(match)) != 0;

Comments are closed.