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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...