I was wondering how the following enum masking works
If I have an Enum structure
public enum DelMask
{
pass = 1,
fail = 2,
abandoned = 4,
distinction = 8,
merit = 16,
defer = 32,
}
I have seen the following code
int pass = 48;
if ((pass & (int)DelMask.defer) > 0)
//Do something
else if ((pass & (int)DelMask.merit ) > 0)
//Do something else
I am wondering can anyone help me figure out how which block will get executed?
Basic bit logic at work here. The integer 48 ends like this in binary:
Defer, 32, is:
Merit, 16, is:
Now when you perform a logical AND (&), the resulting bits are set where they are both in the input:
The result will be 16, so
((pass & (int)DelMask.defer) > 0)will evaluate to true. Bothif‘s will evaluate to true in your example because both flags are present in the input. The second one won’t be evaluated though, because it’s anelse if.