Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working out Enum masks c#

Tags:

c#

enums

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?

like image 221
Wesley Skeen Avatar asked Mar 07 '26 15:03

Wesley Skeen


1 Answers

Basic bit logic at work here. The integer 48 ends like this in binary:

0011 0000

Defer, 32, is:

0010 0000

Merit, 16, is:

0001 0000

Now when you perform a logical AND (&), the resulting bits are set where they are both in the input:

pass & (int)DelMask.defer

0011 0000 
0010 0000
========= & 
0010 0000    

The result will be 16, so ((pass & (int)DelMask.defer) > 0) will evaluate to true. Both if'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 an else if.

like image 144
CodeCaster Avatar answered Mar 09 '26 05:03

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!