FormatWith - String.Format Extension Method

I have a love/hate relationship with String.Format.

On one hand it makes strings easier to read and they can easily be put in an external resource.

On the other hand every bloody time I want to use String.Format, I only realize when I am already halfway through writing the string. I find jumping back to the start to add String.Format is extremely annoying and that it breaks me out of my current train of thought.

FormatWith

FormatWith is an extension method that wraps String.Format. It is the first extension method I wrote and is probably the one I have used the most.

Logger.Write("CheckAccess result for {0} with privilege {1} is {2}.".FormatWith(userId, privilege, result));

An extension method with the same name as a static method on the class causes the C# compiler to get confused, which is the reason why I have called the method FormatWith rather than Format.

public static string FormatWith(this string format, params object[] args)
{
  if (format == null)
    throw new ArgumentNullException("format");
 
  return string.Format(format, args);
}
 
public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
  if (format == null)
    throw new ArgumentNullException("format");
 
  return string.Format(provider, format, args);
}

kick it on DotNetKicks.com

Update:

You may also be interested in FormatWith 2.0.