Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Does the [Flags] Attribute Really Do?

What does applying [Flags] really do?

I know it modifies the behavior of Enum.ToString, but does it do anything else? (e.g. Different compiler or runtime behavior, etc.)


Edit: Yeah, I'm aware that it documents the fact that the enum is intended to be used as bitwise flags, and that it's more logical to apply it to bit flags. I was asking more about concrete behavior changes though, not general programming practices.

like image 242
user541686 Avatar asked May 05 '11 19:05

user541686


People also ask

What does the flags attribute do?

Flags allow an enum value to contain many values. An enum type with the [Flags] attribute can have multiple constant values assigned to it. With Flags, it is still possible to test enums in switches and if-statements. Flags can be removed or added.

What is the role of Flag attribute in enums?

The [Flag] attribute is used when Enum represents a collection of multiple possible values rather than a single value. All the possible combination of values will come. The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value.

Why should you apply the flags attribute to an enum type when you want to store combined values?

Flags allow you to use bitmasking inside your enumeration. This allows you to combine enumeration values, while retaining which ones are specified. This is incorrect, you can use bitmasking even if enum is not marked as Flags .

How do bit flags work?

Bit flags are used for compact representation of small sets of values. Each value is assigned a bit index. All integer numbers with the bit at that index set to 1 are interpreted as sets that include the corresponding member. enum Color { Red = 1 << 0 , Green = 1 << 1 , Blue = 1 << 2 };


2 Answers

From an MSDN article:

It is interesting to note that when Flags is specified, Parse and Format methods feature advanced capabilities.

Likewise, the Parse method can successfully parse a comma-separated string like the one just shown into the proper numeric value.

like image 102
devio Avatar answered Sep 21 '22 09:09

devio


See David M. Kean's post here. This appears to be a language interop issue:

Although C# happily allows users to perform bit operations on enums without the FlagsAttribute, Visual Basic does not. So if you are exposing types to other languages, then marking enums with the FlagsAttribute is a good idea; it also makes it clear that the members of the enum are designed to be used together.

Regards

David

like image 32
Dave Ziegler Avatar answered Sep 19 '22 09:09

Dave Ziegler