Understanding the Flag Enums in C#

Flags Enum Attribute

  1. Use the [Flags] attribute to represent the enum as a bit field.
  2. The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators.
    [Flags]
    public enum SignalColor
    {
        None = 0,//0000
        Red = 1,//0001
        Green = 2,//0010
        Yellow = 4,//0100
        Stop = Red | Yellow//0101
    }
    public class FlagsEnum
    {
        public static void Test()
        {
            //SignalColor.Stop & SignalColor.Red == SignalColor.Red
            if (SignalColor.Stop.HasFlag(SignalColor.Red))
            {
                Console.WriteLine("Red is to stop");
            }
        }
    }

Explanation of the above code

  1. The value of SignalColor.Stop is 0101 in binary (which is 5 in decimal).
  2. The value of SignalColor.Red is 0001 in binary (which is 1 in decimal).

When you perform a bitwise AND operation between SignalColor.Stop (0101) and SignalColor.Red (0001), the result is.

  • 0101 (Stop)
  • 0001 (Red)

Result

0001 (which equals SignalColor.Red)

Summary

The SignalColor enum uses the [Flags] attribute to represent a combination of signal colors using bitwise operations.


Similar Articles