The life of a code monkey

Text

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. 

Posted on Wednesday, June 1 2011. Tagged with: C SharpCConstructorsstring formatstring.Format.netmethod signature
18
Notes
  1. jjidfje liked this
  2. zeate liked this
  3. qizhio liked this
  4. beagirls liked this
  5. dotnetgeek posted this
Got a question or comment? Ask me.
Previous Next