views:

439

answers:

3

I was wondering if Enums with Flag attribute are mostly used for Bitwise operations why not the compilers autogenerate the values if the enum values as not defined.

For eg.

[Flags]
public enum MyColor
{
    Yellow = 1,
    Green = 2,
    Red = 4,
    Blue = 8
}

It would be helpful if the values 1,2,4,8 are autogenerated if they are not assigned. Would like to know your thoughts on this.

+2  A: 

They probably could, but with a compiler of this size they have to take into consideration the time and resources required to implement something vs the potential benefit, especially with syntactic sugar like this. And it is just syntactic sugar because you can write it manually.

Blindy
+6  A: 

This is a little easier:

[Flags]
public enum MyColor
{
    Yellow = 1<<0,
    Green = 1<<1,
    Red = 1<<2,
    Blue = 1<<3
}
danbystrom
How does this answer the question?...
SKG
It saves you the need to calculate the next available value
Ofir
+3  A: 

I expect it is because the FlagsAttribute instance is being compiled alongside, or after, the Enum. That is to say decorating an object with an atribute (like [Flags]) causes the creation of an attribute object, it doesn't modify the base object in a fundamental way.

Also, part of the information stored (for run-time instantiation of the attribute) is the entity to which it refers. It may be that the entity enum must be compiled before its attributes, so an attribute couldn't affect the entity it refers to (in this case enum). I don't know this statement to be true, it's just a guess.

The big take-away is the attributes, like [Flags], are actually entities themselves and not modifications of the decorated type.

Ed Gonzalez