C# Flag Enum
In this chapter you will learn:
- What is flag enum
- How to create and use flag enum
- How to check the combination of flag enum
- Using Bit flags when declaring the 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;/*w w w. j a v a 2s. co 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 www . j av a2 s. co 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;//from www .j ava2s .co 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.
Next chapter...
What you will learn in the next chapter:
- What is an Attribute
- How to use an attribute
- Example for Attribute Targets
- Specifying Multiple Attributes