C# Tip: Don't Concatenate, Use String.Format

24. October 2008 09:57

Something that tends to annoy me, is seeing a ton of string concatenation, such as below.

string mystring = "<a href="\">" +
    ResourceHelper.GetString("somestr", SiteHelper.GetCurrentCulture()) +
    "</a>"; 

The real issue is seeing the above code all on one line, and with the various html markup intersperced with various object variables.  It can be very difficult to follow, especially when you see all this one one line, or not very well broken up.  This leads me to the happy little method known as String.Format(), which takes a format string as its' first parameter, and a set of objects as parameters to be formatted into the string.  Below is the above example rewritten to use String.Format().

string mystring = string.Format(
    "<a href="\">{3}</a>",
    someObject.BasePath,
    otherObject.SomeValue,
    ResourceHelper.GetString("MyResourceKey", SiteHelper.GetCurrentCulture())
); 

The above example is much more readable.  The format string takes numbered parameters starting at 0 and can even take a format string such as for a date.

string formattedString = string.Format(
    "{0:yyyy-MM-dd}{1}{2:0,0.0000}",
    someObject.DateTimeValue,
    someObject.StringValue,
    someObject.DoubleValue
); 

As you can see, using String.Format can make your formatted text much easier to follow and read than inline concatenation.  I know the examples above apply to formatting text into html markup, and acknowledge that this isn't the *only* place where this happens, however it is one of the more common themes I see used over, and over again.  If your string floats off to the right of the screen, and you can't easily follow the concatenation, then string.Format is probably a good idea.  Especially combined with multi-line strings in C# (@"").  Note, if you need a literal curly braces symbol ("{" or "}") simply double the character up ("{{" or "}}").

Tags: , ,

Comments are closed

Tracker1

Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.