views:

401

answers:

4

According to my code a=1, b=2, c=3 etc. I thought the flag would make a=1, b=2, c=4, etc

[Flags]
public enum someEnum { none, a, b, c, d, e, f, }

How do i get what i intended(c=4, e=8)? and what does the [Flags] mean above?

+1  A: 

Flags Attribute indicates that an enumeration can be treated as a bit field; that is, a set of flags.

Svetlozar Angelov
+13  A: 

You can specify values for the enums, this is needed for flags cases:

[Flags]
enum MyFlags {
  Alpha=1,
  Beta=2,
  Gamma=4,
  Delta=8
}

what does the [Flags] mean above?

It means the runtime will support bitwise operations on the values. It makes no difference to the values the compiler will generate. E.g. if you do this

var x = MyFlags.Alpha | MyFlags.Beta;

with the Flags attribute the result of x.ToString() is "Alpha, Beta". Without the attribute it would be 3. Also changes parsing behaviour.

EDIT: Updated with better names, and the compiler doesn't complain using bitwise ops on a non-flags attribute, at least not C#3 or 4 (news to me).

Richard
In addendum: this means that you can have: var flags = MyFlags.a | myFlags.b i.e. "flags" have both values (a and b)
veggerby
When [Flags] is used to identify a combinable enum, it is a convention to have a pluralised name for the enum - myflagsyou can set the underlying type of the enum (default int) to another integral value. e.g:enum myenum : byte
AndyM
BTW, the compiler allows bitwise operations on enums even if the Flags attribute is not specified. It is more an informational attribute than a real constraint (although some classes, like XmlSerializer, require that attribute to work with bitwise combinations)
Thomas Levesque
btw, for this usage it is recommended to also include a `None = 0,` entry (or similar)
Marc Gravell
Instead of setting 1,2,4,8 you can use 1<<0 , 1<<1 , 1<<2 , 1<<3. This is specially useful when you have a lot of enums and you have to define very large numbers.
Paulo Manuel Santos
A: 

[Flags] does not alter the way in which the compiler assigns values to each identifier, it is always your responsibility to make sure that each value is appropriate, whether the enum contains flags or not.

It also does not alter the bitwise operations that the compiler will allow on the enum.

What it does do is alter the behaviour of the Enum.Parse and Enum.ToString methods, to support combinations of values as well as single values, e.g. "a, b, c".

Christian Hayter
+1  A: 

The Flags attribute really only affects the behaviour/output of the ToString(), Parse() and IsDefined() methods on your enumeration.

You can perform bitwise operations without using the Flags attribute, as long as you use powers of two values.

Read this existing question (and answers) for more detailed coverage.

Ash