Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this ?: operator return null?

I wrote this line of code to handle nulls but I still get an "Object reference not set to an instance of an object" error whenever I run this line of code when expectedItem is null. What gives? What's the proper way to write this? Since expectedItem is null, I'd expect expectedItem.ExpectedResultAmount to be null also so this statement should assign an empty string to x.

string x = expectedItem.ExpectedResultAmount != null ? expectedItem.ExpectedResultAmount : "";
like image 204
starvingPhilosopher Avatar asked Mar 26 '26 06:03

starvingPhilosopher


2 Answers

You need to check if expectedItem is not null, not its property

string x = expectedItem != null ? expectedItem.ExpectedResultAmount : "";
like image 182
zerkms Avatar answered Mar 28 '26 19:03

zerkms


You should check both the object instance (expectedItem) and the property (expectedItem.ExpectedResultAmount) as either may fail:

string x = expectedItem != null && expectedItem.ExpectedResultAmount != null ? expectedItem.ExpectedResultAmount : "";
like image 27
Matthew Layton Avatar answered Mar 28 '26 20:03

Matthew Layton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!