Overload ToString() to make debugging easier

Debugging
Image by TaranRampersad via Flickr

When you're debugging code in Visual Studio, you're going to end up setting breakpoints, watching variables, and maybe dumping information to a log file or the immediate window.  Wouldn't it be nice if you could read some of it?

Too often, we wait until we're writing a log entry or trying to peer into the contents of a watched variable to worry about formatting objects.  If you find yourself looking at a particular object or structure more than a couple times, though, consider overloading the ToString() method on that object.  After all, nothing should be better suited to present a default format for an object than the object itself.  Instantly, you'll find that logging and debugging become easier, because when you hover over an instance of that object, you're going to see a meaningful representation of the object.

In this example, you can see that I'm showing some properties and ignoring others - not all of that detail is needed to identify this object, and we're not trying to serialize it, after all, but if I ever wanted to change this, I'd have one method to update.


class ParamInfo
{
public String Name {get; set;}
public Boolean IsOutputParameter { get; set;}
public String TypeName { get; set; }
public Int32 Size { get; set; }
public Int32 Precision { get; set; }
public Int32 Scale { get; set; }

/// <summary>
/// Improve formatting for logging.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("Parameter name=[{0}], type=[{1}]", this.Name, this.TypeName);
}
}

Here's another example where I'm using this technique.

Reblog this post [with Zemanta]

One Reply to “Overload ToString() to make debugging easier”

Comments are closed.