質問

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.

役に立ちましたか?

解決

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.

他のヒント

You should have an == not an !=

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

Try this:

var test = (MyObject == null || string.IsNullOrEmpty(MyObject.Property)
             ? string.Empty : MyObject.Property
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

That happens because MyObject is null and therefore the first condition is false so the second part must be evaluated to know the whole of the condition. Change the line to this:

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

You should prefer readability instead of line-count, e.g.:

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

(the reason for your exception was already explained in other answers)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top