tags:

views:

121

answers:

3

See thread title. Can I safely do something like that without worrying about a NullReferenceException, or is not guaranteed that those boolean expressions will be evaluated left to right?

// can this throw an NRE?
if (obj == null || obj.property == value)
{
   // do something
}
+17  A: 

They will be evaluated left to right, guaranteed. So yes, its safe.

The conditional-OR operator (||) performs a logical-OR of its bool operands, but only evaluates its second operand if necessary.

http://msdn.microsoft.com/en-us/library/6373h346%28VS.71%29.aspx

kekekela
great, thank you
nw
The only caveat would be that if there is a thread that could possibly change the value of object from non-null, to null, between the execution of the left and right evaluations. That would be a rare, yet possible, issue.
umbyersw
Well, it is safe in terms of expression evaluation order. However, it is not thread safe if multiple threads can access the obj variable
Mahol25
+1  A: 

That's perfectly safe to do. If the first expression on the left is true, then the rest isn't evaluated.

DavidGouge
On the left, you mean.
Håvard S
I believe your answer would be correct if it instead read: "...on the *left* is *true*, ..."
umbyersw
DavidGouge
+1  A: 

This is indeed safe. See the C# documentation for || and && (which is of course the opposite, short circuiting for false).

(Regarding "x || y")

if x is true, y is not evaluated (because the result of the OR operation is true no matter what the value of y might be). This is known as "short-circuit" evaluation.

Willfulwizard