C# Flag Enum

Description

We can combine flag enum members.

To prevent ambiguities, members of a combinable enum require explicitly assigned values, typically in powers of two.

Example

We can use Flag enum value to do bitwise operation.


using System;/*  ww w.j av a2 s. c o  m*/

[Flags]
public enum WeekDay{

   Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

}

class Test
{
    static void Main()
    {
        WeekDay day = WeekDay.Saturday | WeekDay.Sunday;
        Console.WriteLine(day);
    }
}

The output:

Example 2

The following code checks the combination of flag enum.


//from  w w w.ja  v a2  s  . c  o m
using System;

[Flags]
public enum WeekDay
{

    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

}

class Test
{
    static void Main()
    {
        WeekDay day = WeekDay.Saturday | WeekDay.Sunday;
        if ((day & WeekDay.Saturday) != 0)
        {
            Console.WriteLine("it is a weekend.");
        }

    }
}

The output:

Bit flags enum


using System;//w ww  . j  a  v  a2 s. c  o  m

[Flags]
enum Color : uint
{
   Red = 0x01, // Bit 0
   Blue = 0x02, // Bit 1
   Yellow = 0x04, // Bit 2
   Green = 0x08 // Bit 3
}

class MainClass
{
   static void Main()
   {
      Color ops = Color.Red | Color.Yellow | Color.Green;
      
      bool UseRed = false, UseBlue   = false, UseYellow  = false, UseGreen = false;

      UseRed = (ops & Color.Red) == Color.Red;
      UseBlue    = (ops & Color.Blue) == Color.Blue;
      UseYellow  = (ops & Color.Yellow) == Color.Yellow;
      UseGreen  = (ops & Color.Green) == Color.Green;

      Console.WriteLine("Option settings:");
      Console.WriteLine("   Use Red    - {0}", UseRed);
      Console.WriteLine("   Use Blue   - {0}", UseBlue);
      Console.WriteLine("   Use Yellow - {0}", UseYellow);
      Console.WriteLine("   Use Green  - {0}", UseGreen);
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor