"if (a() && b != null)" will "a()" always be evaluated?
Solution 1:
Yes, a()
will always be evaluated.
Since the condition is evaluated from left to right, a()
will always be evaluated, but b != null
will only be evaluated if a()
returns true
.
Here's an exact specification reference for you, from the C# Language Specification version 3.0. My emphases and elisions.
7.11.1 Boolean conditional logical operators
When the operands of
&&
or||
are of typebool
[...] the operation is processed as follows:
- The operation
x && y
is evaluated asx ? y : false
. In other words,x
is first evaluated and converted to type bool. Then, ifx
is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.
Solution 2:
Yes, expressions are evaluated from left to right; so a()
will always be called.
See the C# language spec (ECMA 334, paragraph 8.5):
Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.
Solution 3:
The condition is evaluated from left to right. So a()
is always executed, but b
might not be evaluated depending on the result from a()
.
Solution 4:
a()
will always be evaluated. b != null
will only be evaluated if a()
evaluates to true.
This is known as short circuit evaluation.