nw.
nw.

Reputation: 5155

Is it safe to check an object for null and in the same if-statement compare the object's property value?

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
}

Upvotes: 14

Views: 3388

Answers (3)

WillfulWizard
WillfulWizard

Reputation: 5409

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.

Upvotes: 1

DavidGouge
DavidGouge

Reputation: 4623

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

Upvotes: 1

heisenberg
heisenberg

Reputation: 9759

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

Upvotes: 24

Related Questions