14

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.

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If the second operand is itself a Boolean expression, you can spare its evaluation. Anyway, the benefit needs to be confirmed by benchmarking.
2

Per the documentation (emphasis mine):

An expression using the &= assignment operator, such as

x &= y

is equivalent to

x = x & y

except that x is only evaluated once. The & operator performs a bitwise logical AND operation on integral operands and logical AND on bool operands.

And similar for |=.

3 Comments

This answer is misleading. &= and |= are still bitwise operations, even on boolean values; a &= b is not a shorthand for a = a && b. According to sharplab.io, they still use the and and or instructions – which is what's used for bitwise operations – whereas && and || use branching instructions to implement the short-circuiting behaviour.
@absoluteAquarian the answer (the documentation) doesn’t suggest it’s shorthand for the short-circuiting versions?
Apologies, I must have misread your answer. The point that I was trying to make is that the bitwise (&, |) and conditional (&&, ||) operators do not have the same behavior, and someone could have interpreted the answer as such.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.