Use String.Format (C# and VB.NET) instead of Chopping Strings

May 25th, 2007 by Sameer | Filed under .NET articles.

String.Format is just so cool.  It makes your code less spaghetti like and makes it easier to replace string values or add new values.  It also allows you to see from a quick glance what your code does.  It also makes it MUCH easier to update your string and add more parameters to it.  It works similarly to the printf function in C++ that takes a string, and then is followed by parameters that specify what to plug into the string.

Here is a String.Format example (C#):

text1.Text = string.Format("<a href=\"Mylink.aspx?abc=0&Color={0}\">my Link text</a>", myColor);

Isn’t that much nicer than our not so clean string concatenation (C#):


text1.Text = "<a href=\"Mylink.aspx?abc=0&Color=" + myColor + "\">my Link text</a>";

Now if we want to add one more parameter, it’s still so clean!  Note that it is the same syntax for C# and VB.NET

text1.Text = string.Format("<a href=\"Mylink.aspx?abc=0&ID={0}&wl={1}\">my Link text</a>", myColor, myWeight);

However, there are some performance considerations to think about.  In most cases, the minor performance gain is negligible compared to the clarity of code benefits.

Other Interesting Posts

2 Responses to “Use String.Format (C# and VB.NET) instead of Chopping Strings”

  1. Sameer | 30/05/07

    Take a look at how much more readable your code is is after using string.format. This code takes a raw phone number and adds brackets to it for formatting (VB.NET example)

    Before:

    ’strPhone = “(” & strPhone.Substring(0, 3) & “)” & strPhone.Substring(3, 3) & _
    ‘ “-” & strPhone.Substring(6, 4)

    After:

    strPhone = string.Format(”({0}){1}-{2}”, strPhone.Substring(0, 3), strPhone.Substring(3, 3), strPhone.Substring(6, 4))

  2. Sameer | 31/05/07

    Take a look at the performance String.Format at: http://blogs.msdn.com/ricom/archive/2004/03/12/88715.aspx

    In summary, ”
    Even though it’s the worst performing, and we knew that much in advance, both of your CLR Performance Architects concur that #2 [Using String.Format] should be the default choice. In the highly unlikely event that it becomes a perf problem the issue is readily addressable with only modest local changes. Normally you’re just cashing-in on some nice maintainability. We do not alter our choice given the data below”

Share Your Thoughts

Valid XHTML 1.0 Transitional Valid CSS!