In C#, enums can be used with bitwise operators to store and manipulate sets of flags. This is accomplished by decorating the enum with the [Flags] attribute, and defining the enum values as powers of 2. For example:
[Flags] enum MyEnum { None = 0, Flag1 = 1 << 0, // 1 Flag2 = 1 << 1, // 2 Flag3 = 1 << 2, // 4 Flag4 = 1 << 3 // 8 } In this example, each enum value is defined as a power of 2 (i.e. 1 << n), which allows them to be combined using the bitwise OR operator (|) and tested using the bitwise AND operator (&).
For example, to combine two flags:
MyEnum flags = MyEnum.Flag1 | MyEnum.Flag3;
To test if a flag is set:
if ((flags & MyEnum.Flag2) != 0) { // Flag2 is set } To clear a flag:
flags &= ~MyEnum.Flag1;
To toggle a flag:
flags ^= MyEnum.Flag2;
Note that bitwise operations should only be used with Flags enums, and not with enums that represent discrete values.
"C# Enum Flags attribute"
[Flags] public enum MyFlagsEnum { None = 0, Flag1 = 1 << 0, Flag2 = 1 << 1, Flag3 = 1 << 2, // Add more flags using << operation } [Flags] attribute and uses the << operation to define individual flag values."C# Enum bitwise OR operation with Flags"
MyFlagsEnum combinedFlags = MyFlagsEnum.Flag1 | MyFlagsEnum.Flag2;
|) operation to combine flags in an enum marked with the [Flags] attribute."C# Enum bitwise AND operation with Flags"
MyFlagsEnum commonFlags = MyFlagsEnum.Flag1 & MyFlagsEnum.Flag2;
&) operation to find common flags between two enum values marked with the [Flags] attribute."C# Enum bitwise XOR operation with Flags"
MyFlagsEnum exclusiveFlags = MyFlagsEnum.Flag1 ^ MyFlagsEnum.Flag2;
^) operation to get exclusive flags between two enum values with the [Flags] attribute."C# Enum bitwise NOT operation with Flags"
MyFlagsEnum invertedFlags = ~MyFlagsEnum.Flag1;
~) operation to invert the bits of an enum value marked with the [Flags] attribute."C# Enum HasFlag method"
bool hasFlag = myEnumValue.HasFlag(MyFlagsEnum.Flag1);
HasFlag method to check if a specific flag is set in an enum marked with the [Flags] attribute."C# Enum SetFlag method"
myEnumValue |= MyFlagsEnum.Flag1;
|= operator on an enum marked with the [Flags] attribute."C# Enum ClearFlag method"
myEnumValue &= ~MyFlagsEnum.Flag1;
&= operator with bitwise NOT on an enum marked with the [Flags] attribute."C# Enum ToggleFlag method"
myEnumValue ^= MyFlagsEnum.Flag1;
^= operator on an enum marked with the [Flags] attribute."C# Enum Check multiple flags"
bool hasMultipleFlags = (myEnumValue & (MyFlagsEnum.Flag1 | MyFlagsEnum.Flag2)) == (MyFlagsEnum.Flag1 | MyFlagsEnum.Flag2);
&) and equality comparison.razorengine mysql ng-class capture-group logback startup camera reducers asp.net-3.5 hdmi