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 will result in unexpected results. Common practice to make uniqueness is just to mark enum values with power of 2.
For instance Yellow
bitwise or Green
will result in Red
and so on.
MyColors colors = MyColors.Yellow | MyColors.Green;
if (colors == MyColors.Red)
{
Console.WriteLine("Oops!")
}
Also note Flags
attribute does nothing here, it gives the impression that you can use bitwise or.