Assume myObj is null. Is it safe to write this?
if(myObj != null && myObj.SomeString != null)
I know some languages won't execute the second expression because the && evaluates to false before the second part is executed.
Yes. In C# &&
and ||
are short-circuiting and thus evaluates the right side only if the left side doesn't already determine the result. The operators &
and |
on the other hand don't short-circuit and always evaluate both sides.
The spec says:
The
&&
and||
operators are called the conditional logical operators. They are also called the “shortcircuiting” logical operators.
...
The operationx && y
corresponds to the operationx & y
, except thaty
is evaluated only ifx
istrue
...
The operationx && y
is evaluated as(bool)x ? (bool)y : false
. In other words,x
is first evaluated and converted to typebool
. Then, ifx
istrue
,y
is evaluated and converted to typebool
, and this becomes the result of the operation. Otherwise, the result of the operation isfalse
.
(C# Language Specification Version 4.0 - 7.12 Conditional logical operators)
One interesting property of &&
and ||
is that they are short circuiting even if they don't operate on bools, but types where the user overloaded the operators &
or |
together with the true
and false
operator.
The operation
x && y
is evaluated asT.false((T)x) ? (T)x : T.&((T)x, y)
, whereT.false((T)x)
is an invocation of theoperator false
declared inT
, andT.&((T)x
, y) is an invocation of the selectedoperator &
. In addition, the value (T)x shall only be evaluated once.In other words,
x
is first evaluated and converted to typeT
andoperator false
is invoked on the result to determine ifx
is definitelyfalse
.
Then, ifx
is definitelyfalse
, the result of the operation is the value previously computed forx
converted to typeT
.
Otherwise,y
is evaluated, and the selected operator&
is invoked on the value previously computed forx
converted to typeT
and the value computed fory
to produce the result of the operation.
(C# Language Specification Version 4.0 - 7.12.2 User-defined conditional logical operators)