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 : "";
You need to check if expectedItem is not null, not its property
string x = expectedItem != null ? expectedItem.ExpectedResultAmount : "";
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 : "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With