Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle null exceptions when concatenating a string in C#?

Tags:

c#

null

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.

like image 771
Ammar Avatar asked Dec 02 '25 05:12

Ammar


1 Answers

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.

like image 90
dtb Avatar answered Dec 03 '25 19:12

dtb



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!