02 string.Format() extension method.

A nice use for an extension method is string.Format(), so instead of

var formatted = string.Format("My Format string {0}, {1}", firstParameter, secondParameter);

you may simply use

var formatted = "My Format string {0}, {1}"
  .Format(firstParameter, secondParameter); 

An example implementation may look like the following:

public static class StringExtensions
{
  public static string Format(this string format, params object[] objects)
  {
    if (objects.Length == 0)
      return format;
 
    try
    {
      return string.Format(format, objects);
    }
    catch (Exception e)
    {
      return e.Message;
    }
  }
}

The above code catches all exceptions that happen in the formatting process. This is useful in cases when the format string may be invalid and might not match the arguments provided.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Cool code

This code is really cool. While it's very short, it can save me hours of hitting backspace to return to the beginning of the formatted string, just because I usually understand that I need more placeholders in middle of the string formatting, not at the beginning. Thanks.