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?
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.
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With