Check if child object value exists NullReferenceException

Viewed 35

I'm pretty new to C#. While attempting to set a local variable value, I'm running into a NullReferenceException. It appears that the Buyer object is null, which I'm assuming is why it can't figure out the Buyer.Username value. What I'm not sure about is how to check if Buyer is not null AND that the Buyer.Username has a non-null value (in the most simple way possible). Unfortunately, I'm using C# 7.3 which doesn't appear to have support for the ?? operator.

BuyerUserName = string.IsNullOrEmpty(model.Transactions[i].Buyer.Username) ? "" : model.Transactions[i].Buyer.Username
1 Answers

Both ?? and ?. were introduced in C# 6, so you can use them:

BuyerUserName = model.Transactions[i].Buyer?.Username ?? string.Empty;

But even without that, there is nothing wrong with taking more than one line to do something, and you could just use an if statement:

var buyer = model.Transactions[i].Buyer;
if (buyer != null && buyer.Username != null)
    BuyerUserName = buyer.Username;
else
    BuyerUserName = string.Empty;
Related