5

Given an enum with 4 elements

enum fontType {bold,italic,underlined,struck}

and two variables of this enumeration type called enum1 and enum2 that are assigned as follows

fontType enum1=fontType.bold | fontType.italic;
fontType enum2=fontType.underlined & fontType.struck;

Why is enum1 = 'italic' and enum2 = 'underlined' on output?

deemel
  • 1,006
  • 5
  • 17
  • 34
  • 2
    http://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c –  Dec 04 '13 at 15:17

1 Answers1

11

If you're going to use the enum as a bitmap like this, then the members need to be given values which use a different bit each:

[Flags]
enum MyEnum
{
   Bold = 0x01,
   Italic = 0x02,
   Underlined = 0x04,
   Struck = 0x08
}

By default, they've been given the numbers 0,1,2,3 - the first does nothing, and the second two overlap with the last.

As mentioned in the comments, you should also add the [Flags] attribute to the enum definition, so that if you do ToString() you get a properly formatted result (and so that everybody knows how you're using the enum) - if won't affect the way it works if you don't, though.

Will Dean
  • 39,055
  • 11
  • 90
  • 118