Test flags-style enum values with bitwise logic C# with Example



Test flags-style enum values with bitwise logic C# with 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); 

0 Comment's

Comment Form

Submit Comment