String format constructors
Recently I noticed that I had a class with a constructor that had a single string parameter. For discussion lets assume that the class looked something like this.
public class SomeException : Exception
{
public SomeException(string message)
: base(message)
{ }
}
In my code I found several calls that looked something like:
throw new SomeException(string.Format("Could not find {0} in {1}", item, container));
This is perfectly acceptable way of creating an object but I wanted something a little cleaner. I modified the constructor’s signature to look more like the string.Format signature:
public class SomeException : Exception
{
public SomeException(string messageFormat, params string[] args)
: base(string.Format(messageFormat, args))
{ }
}
This then changes the previous constructor call to:
throw new SomeException("Could not find {0} in {1}", item, container);
It may not be as obvious that the constructor is doing a string.Format on the parameters, but I don’t think it that far of a stretch for another program to see what is happening in the code.