Conditional Operators vs Logical Assignment Operators


This is just a little note to myself to remember that assigning the result of a conditional operation (a = a && b;) is not the same as using a logical assignment operator (a &= b;).

First: The conditional operators (&&, ||) work on the boolean results of their operands – that is, the operands are evaluated as booleans and the operator performs a logical AND or a logical OR on the two boolean values.
In contrast, the logical assignment operators (&=, |=) perform bitwise AND and OR operations between the operands.

Second: The conditional operators will short-circuit, the assignment operators do not. In the statement

a = a || b;

if a initially evaluates to false, then b is not evaluated. Whereas in the statement

a |= b;

b will be evaluated whether a is true or false.

There are very few cases where the first difference is likely to matter, however, it is easy to get caught by the second difference.

Note: The null-conditional operators (?., ?[]) also short-circuit – which is what will make them useful – when/if I get upgraded to C# 6.0.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s