I have came across this question: What does the [Flags] Enum Attribute mean in C#?
And one thing I have been wondering, using the accepted answer's example, what will happen if I declare:
[Flags]
public enum MyColors
{
Yellow = 1,
Green = 2,
Red = 3,
Blue = 4
}
Will the following steps in that example resulting an error? If no, how can I get to MyColors.Red?
It is not necessary to assign sequential values to Enum members. They can have any values. In the above example, we declared an enum PrintMedia .
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.
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 Flags attribute doesn't actually do anything to enum itself or affect how it's used in code. The one and only thing that the Flags attribute does affect is the output of the ToString method. The other purpose of the Flags attribute is to indicate to the developer how they should use the enum. Your example will not cause any error; it's just stupid code. The rules are very simple:
To elaborate of jdphenix's answer, remember that the [Flags]
attribute doesn't actually do any magic. It just adds a purely cosmetic marker on the enum that lets other functions (by default, only an enum's ToString
implementation) to treat the enum as a Flags enum.
Regardless of the attribute, an enum is still just a number, by default an Int32, with some syntactic sugar around it. So if you define your enum as you did, doing
MyColors newColor = MyColors.Yellow | MyColors.Green
would just do a bitwise OR operation on 1 and 2. The magic that is bitwise enums isn't in the attribute, but in the fact that powers of 2 allows you to "switch" a certain bit on and off. Using ordinal numbers will switch off bits that are a part of the binary representation of more than one enum value, making the result of the bitwise operation meaningless.
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