C# Tips and Tricks #3 – [Flags] attribute for Enum in C#

Ever wondered what is Flags attribute in C#? . Here’s the post that explains with an example on what is Flags attribute and how you can use it with enum in C#.

What is Flags Attribute for Enums in C# ?

Enum in c# supports the Flags attribute which can be used whenever the enum result represents a collection of values instead of a single value . This allows the developers to group the enum values. Assume that we have an enum with the following entries

public enum Colors
{
        
        Red = 1,
        Blue = 2,
        Green = 4,
        None = 5
}

When we have a code like the one shown below where the colors allowed can be either Red , Green or Blue . The ToString() will result in the value “7”.

var ColorsAllowed = Colors.Red | Colors.Green | Colors.Blue;
Console.WriteLine(ColorsAllowed.ToString());

How about nice representation of the result of the above code with the ToString() which displays the values Red , Green , Blue as allowed colors instead of 7 ? This is where the Flags attribute comes in to picture . Below is the same enum defined with the Flags attribute .

[Flags]
public enum Colors
{
        Red = 1,
        Blue = 2,
        Green = 4,
        None = 5 
}

The result of the colorsAllowed will now be Red , Green , Blue as shown in the below screenshot. image

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...