Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 743
Zaki Avatar asked Mar 01 '13 11:03

Zaki


4 Answers

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.

like image 50
Jon Skeet Avatar answered Nov 16 '22 00:11

Jon Skeet


You should have an == not an !=

var test = (MyObject == null || string.IsNullOrEmpty(MyObject.Property) ? string.Empty : MyObject.Property
like image 31
Dave Bish Avatar answered Nov 15 '22 22:11

Dave Bish


Try this:

var test = (MyObject == null || string.IsNullOrEmpty(MyObject.Property)
             ? string.Empty : MyObject.Property
like image 2
Hamlet Hakobyan Avatar answered Nov 16 '22 00:11

Hamlet Hakobyan


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

Here you say.

If my object is not null. or string.IsNullOrEmpty(MyObject.Property)

Which means that if MyObject is null he will try to execute the second part.

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

This won't throw null exception

like image 2
Evelie Avatar answered Nov 15 '22 22:11

Evelie