c# enum question

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello ,

I have declared following enum color type. I am not sure why the
Console.Writeline(color.white.ToString()) prints different outputs.

public enum color {red, blue, white=red|blue};
public static void Main()
{
color c = color.red & color.white;
Console.WriteLine((c).ToString());

With "&" the above outputs red but if you change to "|", it prints "blue".

With little bit more playing around, if I have even number of or'd colors in
the white it prints the last one, if I have odd numbers of or'd color in
white then it prints white


Try following for amusement:

public enum color {red, blue, green, brown, orange,
white=red|blue|green|brown|orange};
Console.WriteLine((color.white).ToString());

public enum color {red, blue, green, brown, orange,
white=red|blue|green|brown};
Console.WriteLine((color.white).ToString());

Can someone please hightlight on this behavior of enums.

Thanks,
Priya.
 
public enum color {red, blue, white=red|blue};

If you want to be able to OR different enum members together you
should set their values to powers of 2.

[Flags]
public enum color {red = 1, blue = 2, white=red|blue};

public static void Main()
{
color c = color.red & color.white;
Console.WriteLine((c).ToString());
With "&" the above outputs red

Right, because red is zero and anything AND zero is zero, i.e. red.

but if you change to "|", it prints "blue".

Because both blue and white had the value 1, and ORing with red (zero)
changes nothing. So the first member with the value 1, i.e. blue, is
printed.


Mattias
 
Back
Top