Home > DeveloperSection > Forums > String.Format with null values C#
Chintoo Semi

Total Post:135

Points:947
Posted on    December-12-2013 1:30 AM

 C# C# 
Ratings:


 1 Reply(s)
 4004  View(s)
Rate this:

I want to format an address. Here is my code:

address = String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}",

                        postalAddress.Line1,

                        postalAddress.Line2,

                        postalAddress.Line3,

                        postalAddress.Line4,

                        postalAddress.Suburb,

                        postalAddress.StateCode,

                        postalAddress.Pcode);

Unfortunately this produces 116 Knox St, , , , Watson, ACT, 2602 when Line2, Line3, Line4 are null. How can I handle the nulls to get a results like 116 Knox St, Watson, ACT, 2602?


Pravesh Singh

Total Post:411

Points:2881
Posted on    December-12-2013 2:14 AM

Hi Chintoo,

You can try this :

StringBuilder sb = new StringBuilder();

List<string> addressParts = new List<string> { postalAddress.Line1, postalAddress.Line2, postalAddress.Line3, postalAddress.Line4, postalAddress.Suburb, postalAddress.StateCode, postalAddress.Pcode };

addressParts.ForEach(x => sb.Append(String.IsNullOrEmpty(x) ? "" : ", " + x));

string address = sb.ToString().Trim(',');


Hope this will solve your problem.

Don't want to miss updates? Please click the below button!

Follow MindStick