Search code examples
c#null-check

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


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)
    ...

Solution

  • 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.