CSharp examples for Custom Type:Enum
You can combine enum members.
To prevent ambiguities, members of a combinable enum require explicitly assigned values, typically in powers of two.
For example:
[Flags]
public enum Directions { None=0, Left=1, Right=2, Top=4, Bottom=8 }
To work with combined enum values, you use bitwise operators, such as | and &.
These operate on the underlying integral values:
[Flags] public enum Directions { None=0, Left=1, Right=2, Top=4, Bottom=8 } Directions leftRight = Directions.Left | Directions.Right; if ((leftRight & Directions.Left) != 0) Console.WriteLine ("Includes Left"); // Includes Left string formatted = leftRight.ToString(); // "Left, Right" Directions s = Directions.Left; s |= Directions.Right; Console.WriteLine (s == leftRight); // True s ^= Directions.Right; // Toggles Directions.Right Console.WriteLine (s); // Left
By convention, a combinable enum type is given a plural rather than singular name.
You can include combination members within an enum declaration itself:
[Flags]
public enum Directions
{
None=0,
Left=1, Right=2, Top=4, Bottom=8,
LeftRight = Left | Right,
TopBottom = Top | Bottom,
All = LeftRight | TopBottom
}