Formatting strings is a very common task in .NET development. Examples include formatting dates and currencies, composing a HTML response, creating error messages, etc. One of the downsides of string formatting is that if done incorrectly, you can end up with subtle bugs that won't be detected until runtime at which point, the application usually crashes with an exception.

Take the following code sample which comes from a real world application. It compiles fine and most of the time, it also runs without any problems However, once in a while, there is a customer complaint that the application crashes. It turns out that the if part of the code is rarely executed and because it isn't a common scenario, it wasn't tested.

So, what is the problem? If you look closely at line 6 below where the string body is formatted, the second format item which is supposed to be the user's name is missing. As I mentioned above, there is no compiler warning or error to tell the developer about this problem. It's usually found during testing or worse case, in production.

   1: protected void btnSubmit_Click(object sender, EventArgs e)
   2: {
   3:     if (isEditingPost)
   4:     {
   5:         string body = txtBody.Value;
   6:         body += string.Format("<p>-- {0}: post edited by {1}.</p>",
   7:            DateTime.Now.ToString());
   8:         // edit an existing post
   9:         Post.UpdatePost(postID, txtTitle.Text, body);
  10:         panInput.Visible = false;
  11:         panFeedback.Visible = true;
  12:     }
  13:     else
  14:     {
  15:         // Rest of code not shown

In Team System 2010, we have added a new rule to Code Analysis that detects this exact problem. When I run Code Analysis over the code above, it clearly warns me that I'm missing a format item:

warning: CA2241 : Microsoft.Usage : Method 'AddEditPost.btnSubmit_Click(object, EventArgs)' calls 'string.Format(string, object)' and does not provide an argument for format item "{1}". The provided format string is: '"<p>-- {0}: post edited by {1}.</p>"'

This feature is available in Visual Studio Team System 2010 Beta 1. Feel free to download the beta and if you have any feedback on this feature, please leave me a comment.

Habib Heydarian.