CSharp - Enum Flags Enums

Introduction

You can combine enum members to represent the combination of two enum values.

You must mark the enum as Flags to get proper string representation and assign members some values, typically in powers of two. For example:

[Flags]
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:

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
}

Demo

using System;
[Flags]/*  www  . j  av  a  2 s.  co  m*/
enum Directions {
   None=0, Left=1, Right=2, Top=4, Bottom=8
}

class MainClass
{
   public static void Main(string[] args)
   {
        Directions leftRight = Directions.Left | Directions.Right;
        
        if ((leftRight & Directions.Left) != 0)
             Console.WriteLine ("Includes Left");     
        
        string formatted = leftRight.ToString();   
        
        Directions s = Directions.Left;
        s |= Directions.Right;
        Console.WriteLine (s == leftRight);   
        
        s ^= Directions.Right;               
        Console.WriteLine (s);               

   }
}

Result