Can I include null-checking an object as another conditional in OR statement? [duplicate]

StackOverflow https://stackoverflow.com/questions/14308650

  •  15-01-2022
  •  | 
  •  

Question

Possible Duplicate:
Is relying on && short-circuiting safe in .NET?

I wasn't sure how to phrase the title of the question correctly, but it's very simple to explain with a single line of code:

if (someObject == null || someObject.someProperty)
    ...

Can I do that? Or this one:

if (someObject != null && someObject.someProperty)
    ...
Was it helpful?

Solution 2

Yes, this is safe. || and && are short-circuiting operators. From the MSDN Library:

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

The operation

x || y

corresponds to the operation

x | y

except that 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.

OTHER TIPS

Yes.

The second operand will only be evaluated if the first operand is false.

Obviously, though, the second operand must also be a boolean.

Similarly, && will only evaluate the second operand if the first operand is true.

This is called short-circuiting.

Yes, it is common practice to use null-checking in an if statement, usually with an AND.

This is valid because the statement will short-circuit and end if the first is true.

Both these are valid:

if(something != null && something.Bool)
  ...

if(something != null || something.Bool)
  ...

Yes, || and && both short-circuit. Indeed, you occasionally see people writing code like this:

x != null && x.f();

Which is equivalent to:

if(x != null) x.f();

(Probably not a good idea most of the time - it's not good for readability.)

Yes you can, but which one you want depends on the semantics you're after.

In the first case, your condition will operation if there's no object at all or if the property returns true. Basically the absence of an instance implies the conditional logic should execute.

In the second case, the absence of an instance will NOT cause your conditional to run; in this case, you must both have an instance and the property must evaluate to true.

I dealt with this very same thing today when loading user preferences. I had to decide if the preference was "checked" or not, and since we may add new preferences (without adding rows for each user for that preference to the database), I chose the latter condition as that met my use case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top