Search code examples
c#monodevelopbitwise-operatorsboolean-logic

MonoDevelop suggests turning if statements into bitwise operations


MonoDevelop suggests turning this:

if (someBoolVar)
    anotherBoolVar = true;

into this:

anotherBoolVar |= someBoolVar;

It also does it when I set anotherBoolVar to false instead:

if (someBoolVar)
    anotherBoolVar = false;

becomes:

anotherBoolVar &= !someBoolVar;

Can someone explain how these statements are equal?


Solution

  • Well, functionally they're equivalent.

    In the first case you want to set anotherBoolVar to true if someBoolVar is true, regardless of what value anotherBoolVar currently has, the replacement expression does that.

    It is short for this:

    anotherBoolVar = anotherBoolVar | someBoolVar;
    

    The second replacement also does the same as the code it replaces, and is short for this:

    anotherBoolVar = anotherBoolVar & (!someBoolVar);
    

    The solution is hidden in the "bitwise" nature of boolean variables in this case. To and with an inverted value (~ inverts the someBoolVar) will effectively say "keep all bits that are set in !someBoolVar and clear out the rest", meaning that if someBoolVar is true, it will be inverted to false, and you'll effectively clear out anotherBoolVar.


    Now, should you do this ?

    In my opinion, no. The code is more readable as-is. Keep, and possibly even look for a way to ask MonoDevelop to not suggest these things in the future.