I have this line of code that can throw null exceptions.
singleAddress.FullAddress = cc.MailingAddressStreet1.ToString() + " " +
cc.MailingAddressCity.ToString() + " " +
cc.MailingAddressState.ToString() + " " +
cc.MailingAddressZip.ToString() + " " +
cc.MailingAddressCountry.ToString();
I know that I can fix it by adding if statements to check if it is null. But is there a better recommended way to do it?
I just want to learn how to handle such exceptions better (and not have to write more code than I need to). Thanks in advance.
You can use the String.Join Method:
if (cc != null)
{
singleAddress.FullAddress = string.Join(" ",
cc.MailingAddressStreet1,
cc.MailingAddressCity,
cc.MailingAddressState,
cc.MailingAddressZip,
cc.MailingAddressCountry);
}
The String.Join Method takes a variable number of object arguments and calls the Object.ToString Method on each argument that is not null.
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