STRING.FORMAT WITH NULL VALUES C#

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
C# 
C#
 5296  View(s)
Ratings:
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?
  1. Pravesh Singh

    Post:412

    Points:2888
    Re: String.Format with null values C#

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!