C# Language Enum Test flags-style enum values with bitwise logic

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A flags-style enum value needs to be tested with bitwise logic because it may not match any single value.

[Flags]
enum FlagsEnum
{
    Option1 = 1,
    Option2 = 2,
    Option3 = 4,
    Option2And3 = Option2 | Option3;

    Default = Option1 | Option3,
}

The Default value is actually a combination of two others merged with a bitwise OR. Therefore to test for the presence of a flag we need to use a bitwise AND.

var value = FlagsEnum.Default;

bool isOption2And3Set = (value & FlagsEnum.Option2And3) == FlagsEnum.Option2And3;

Assert.True(isOption2And3Set);


Got any C# Language Question?