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?
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?
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.