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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

... and [Flags] on the enum as well.
Yes, if you omit [Flags] then the .ToString() doesn't work as well as it could (it just gives you the numeric value rather than each set flag name)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.