I found with or without flags attributes, I can do bit operation if I defined the following enum
enum TestType
{
None = 0x0,
Type1 = 0x1,
Type2 = 0x2
}
I am wondering why we need flags attribute?
Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.
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.
Feature flags allow toggling multiple features of an application without having to redeploy the application. One or more feature flags can be defined declaratively as part of the application's config file that can control feature availability.
C# will treat them the same either way, but C# isn't the only consumer:
PropertyGrid
will render it differently to allow combinationsXmlSerializer
will accept / reject delimited combinations based on this flagEnum.Parse
likewise (from string), and the enum's .ToString()
will behave differentlyMore importantly, though, it is an expression of intent to other developers (and code); this is meant to be treated as combinations, not exclusive values.
Sometimes bit combinations of enum
values are meaningful (like FileAccess
- read, write, read+write), sometimes they are not (usually). So [Flags]
is descriptive way to store in metadata information that bit operations are meaningful on this enum type. There are several consumers of this attribute, for example ToString
of that enum.
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