10

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œur
  • 37,241
  • 25
  • 195
  • 267
user496949
  • 83,087
  • 147
  • 309
  • 426
  • possible duplicate of [Enum Flags Attribute](http://stackoverflow.com/questions/8447/enum-flags-attribute) – BoltClock Feb 11 '11 at 10:28
  • 1
    Actually, I don't think it is a dupe; that dup doesn't *touch* on why it is needed; all of the examples there would work the same either way – Marc Gravell Feb 11 '11 at 10:29
  • 2
    @Marc: Hmm, I just finished looking at some of the answers and you do have a point there. – BoltClock Feb 11 '11 at 10:30

2 Answers2

18

C# will treat them the same either way, but C# isn't the only consumer:

  • PropertyGrid will render it differently to allow combinations
  • XmlSerializer will accept / reject delimited combinations based on this flag
  • Enum.Parse likewise (from string), and the enum's .ToString() will behave differently
  • lots of other code that displays or processes the value will treat them differently

More importantly, though, it is an expression of intent to other developers (and code); this is meant to be treated as combinations, not exclusive values.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

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.

Andrey
  • 59,039
  • 12
  • 119
  • 163