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.
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.
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.
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 .
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 };
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With