I have an Address object that has properties AddressLine1, AddressLine2, Suburb, State, ZipCode. (there are more but this is enough for the example). Also, each of these properties are strings. And I'm using C# 3.0.
I'm wanting to represent it as a string but as I'm doing that I'm finding that I'm creating a method with a high cyclomatic complexity due to all the if-statements...
Assuming the string assigned to each property is the same as the name of the property (ie AddressLine1 = "AddressLine1")...I want the address to be represented as follows:
"AddressLine1 AddressLine2 Suburb State ZipCode".
Now, the original way I had done this was by a simple String.Format()
String.Format("{0} {1} {2} {3} {4}", address.AddressLine1,
address.AddressLine2, address.Suburb, address.State, address.ZipCode);
This is all well and good until I've found that some of these fields can be empty...in particular AddressLine2. The result is additional unneeded spaces...which are particularly annoying when you get several in a row.
To get around this issue, and the only solution I can think of, I've had to build the string manually and only add the address properties to the string if they are not null or empty.
ie
string addressAsString = String.Empty;
if (!String.IsNullOrEmpty(address.AddressLine1))
{
addressAsString += String.Format("{0}", address.AddressLine1);
}
if(!String.IsNullOrEmpty(address.AddressLine2))
{
addressAsString += String.Format(" {0}", address.AddressLine2);
}
etc....
Is there a more elegant and/or concise way to achieve this that I'm not thinking about? My solution just feels messy and bloated...but I can't think of a better way to do it...
For all I know, this is my only option given what I want to do...but I just thought I'd throw this out there to see if someone with more experience than me knows of a better way. If theres no better option then oh well...but if there is, then I'll get to learn something I didn't know before.
Thanks in advance!