I would do something like this:
public override string ToString() { string returnValue = string.empty; if (string.IsNullOrWhiteSpace(Country)) return returnValue; // Note: this is a change from the original code // That could have returned NULL. But I think the // intent of the function is to always return some // form of string. returnValue = string.Format("{0}", Country); if (string.IsNullOrWhiteSpace(City)) return returnValue; returnValue += string.Format(", city {0}", City); if (string.IsNullOrWhiteSpace(Street)) return returnValue; returnValue += string.Format(", street {0}", Street); if (string.IsNullOrWhiteSpace(Block)) return returnValue; returnValue += string.Format(", block {0}", Block); if (!string.IsNullOrWhiteSpace(Building)) returnValue += string.Format(", building {0}", Building); if (!string.IsNullOrWhiteSpace(Latitude) && !string.IsNullOrWhiteSpace(Longitude)) returnValue += string.Format(", coordinates {0}:{1}", Latitude, Longitude); return returnValue; }
If you want to compress this slightly. Though I am in two minds weather this is worth it or not:
public class Pair { public Pair(string v, string f) { this.Value =v; this.Format = f;} public string Value { get; private set; } public string Format { get; private set; } }; public override string ToString() { string returnValue = string.empty; string[] address = {new Pair(Country, "{0}"), new Pair(City, ", city {0}"), new Pair(Street, ", street {0}"), new Pair(Block, ", block {0}") }; foreach(Pair loop in address) { if (string.IsNullOrWhiteSpace(loop.Value)) return returnValue; returnValue += string.Format(loop.Format, loop.Value); } if (!string.IsNullOrWhiteSpace(Building)) returnValue += string.Format(", building {0}", Building); if (!string.IsNullOrWhiteSpace(Latitude) && !string.IsNullOrWhiteSpace(Longitude)) returnValue += string.Format(", coordinates {0}:{1}", Latitude, Longitude); return returnValue; }
return Countryyou are always returning a NULL or an empty string. In which case you may want to make that explicitreturn string.emptyjust to show that it is nothing that is being returned. \$\endgroup\$