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.