Inline If Instruction - Short Circuit

As I understand and read, you can use a short circuit in the if statement (& & or ||) so that the second condition does not work. and if you want both conditions to work, you would use single operands (& or |).

Say if I have an inline if statement, as shown below:

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

This will throw an error object referenceif MyObject is NULL, which in my opinion should not, since I am using a short circuit. Can someone explain this.

+5
source share
6 answers

You are using the wrong condition. This part:

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

it should be:

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

RHS || , . , , MyObject .

EDIT: MyObject != null, :

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

2- 3- , .

+13

== not an!=

var test = (MyObject == null || string.IsNullOrEmpty(MyObject.Property) ? string.Empty : MyObject.Property
+3

:

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

.

. string.IsNullOrEmpty(MyObject.Property)

, MyObject null, .

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

null

+2

, MyObject null, false, , . :

MyObject != null && string.IsNullOrEmpty(MyObject.Property)
+2

You should prefer readability over number of lines, for example:

string prop = string.Empty;
if(MyObject != null && MyObject.Property != null)
    prop = MyObject.Property;

(the reason for your exclusion has already been explained in other answers)

+1
source

All Articles