C# bitwise equal bool operator

Apache81 picture Apache81 · Jul 31, 2015 · Viewed 8.9k times · Source

Boolean in C# are 1 byte variables. And because bool are shortcuts for the Boolean class, I would expect that the &=, |= operations have been overridden to let them work with the boolean types but I'm not so sure about it. There is nothing like &&= or ||= to be used.

Here's my question, doing something like:

bool result = condition;
result &= condition1;
result &= condition2;

will work but is it just because the bool will be 00000000 for false and 00000001 for true or because underneath the bool class will use something like &&= and ||= when the previous are called? Is it actually safe to use the previous notations or is better to use

bool result = condition;
result = result && condition1;
result = result && condition2;

to avoid any strange behavior?

Please note that conditions could be something like A >= B or any other possible check that will return a bool.

Answer

Patrick Hofman picture Patrick Hofman · Jul 31, 2015

As far as I can read in this SO post, the only real difference between bitwise operators and logical operators on booleans is that the latter won't evaluate the right side operand if the left side operand is false.

That means that if you have two booleans, there won't be much difference. If you have two methods, the last one doesn't get executed using logical operators, but it does with binary operators.