What is the use of [Flags] Enum Attribute in C#?

Many of the developers are not aware what exactly the [Flags]-attribute does. What is the use of [Flags] Enum Attribute in C#?Here I am going to explain what is the use of of [Flags] Enum Attribute.

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.

Example:

var vehicles= vehicle.car| vehicle.bus | vehicle.bike;

Note that the [Flags] attribute doesn’t enable this by itself – all it does is allow a nice representation by the .ToString() method:

enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }

...

var str1 = (Suits.Spades | Suits.Diamonds).ToString();
// "5"
var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
// "Spades, Diamonds"

It’s also important to note that [Flags] doesn’t automatically make enumeration values ??equal to two. If you omit numeric values, the enumeration will not work as one might expect in single-bit operations, because by default the values ??start with 0 and increase.

Leave a Reply

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