Logical operators on enums

deemel

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?

Will Dean

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related