Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# problem with flags

I have an enum (flag)

[Flags]
public enum DisplayMode
{
    None,
    Dim,
    Inverted,
    Parse,
    Italics,
    Bold
}

I want to assign two of the flags to a variable, like this:

var displayFlags = DisplayMode.Parse | DisplayMode.Inverted;

However, when I debug and hover over this variable immediately after it is assigned, it says displayFlags is DisplayMode.Dim | DisplayMode.Inverted.

What am I missing/not understanding?

like image 965
Chev Avatar asked Jul 19 '26 09:07

Chev


1 Answers

You've missed assigning the flags sensible values, e.g.:

[Flags]
public enum DisplayMode
{
    None = 0,
    Dim = 1,
    Inverted = 2,
    Parse = 4,
    Italics = 8,
    Bold = 16
}

That way each value has a separate bit in the numeric representation.

If you don't trust your ability to double values, you can use bit shifting:

[Flags]
public enum DisplayMode
{
    None = 0,
    Dim =      1 << 0,
    Inverted = 1 << 1,
    Parse =    1 << 2,
    Italics =  1 << 3,
    Bold =     1 << 4
}

From the documentation from FlagsAttribute:

Guidelines for FlagsAttribute and Enum

  • Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

  • Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.

...

like image 169
Jon Skeet Avatar answered Jul 22 '26 01:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!