Search code examples
c#if-statementinlineshort-circuiting

Inline If statement - short-circuiting


As I understand and read you can use short circuiting in if statement (&& or ||) in order for second condition not to fire. and if you want both condition to fire you would use single operands (& or |).

So say if I have inline if statement as below :

var test = (MyObject != null || string.IsNullOrEmpty(MyObject.Property)) ? string.Empty : MyObject.Property;

This will throw object reference error if MyObject is null, which in my opinion should not as I am using short circuiting. Can someone please explain this.


Solution

  • You're using the wrong condition. This part:

    MyObject != null || string.IsNullOrEmpty(MyObject.Property)
    

    should be:

    MyObject == null || string.IsNullOrEmpty(MyObject.Property)
    

    The RHS of an || only executes if the left hand is false. You want it to only execute if MyObject is not null.

    EDIT: If you really want the MyObject != null part, you could change the whole thing to:

    var test = MyObject != null && !string.IsNullOrEmpty(MyObject.Property)
           ? MyObject.Property : "";
    

    Note the reversal of the 2nd and 3rd operands of the conditional operator too though.