C # And assignment operator (& =) with bitwise enumerations

I use bitwise enumeration to return a value from a function

[Flags] private enum PatientRecord { NoRecord=0x0, SameEnrollmentDate=0x1, SameScreeningDate=0x2 } 

and have a function with

 var returnVar = PatientRecord.NoRecord; .... if (condition...) { returnVar &= PatientRecord.SameEnrollmentDate; } return returnVar 

The debugger shows that returnVar has the same value before and after AND the assignment statement is executed (be it PatientRecord.NoRecord (0) or PatientRecord.SameScreeningDate (2)).

why is this so, and are there any solutions more accurately than:

 returnVar = returnVar & PatientRecord.SameEnrollmentDate; 

Thanks.

+4
source share
1 answer

You want a bitwise OR ( | ), not a bitwise AND ( & ):

 var returnVar = PatientRecord.NoRecord; .... if (condition...) { returnVar |= PatientRecord.SameEnrollmentDate; // ^ Bitwise OR assignment } 

E'ing with zero ( NoRecord=0x0 ) will always lead to zero.

+3
source

Source: https://habr.com/ru/post/1485250/


All Articles