July 03, 2009

Improving the Debugger Experience Using Attributes

Debugging an application is not always the most fun experience out there.  Typically if you are debugging you are trying to dig into a problem, and more than likely deadlines are looming near.  Therefore, anything to make the process a bit easier, is usually a welcomed benefit.

Default Functionality

One of my biggest pet-peeves when it comes to the behavior of the debugger is how objects are explored. When debugging custom objects, the default view after mousing over simply provides the class name, not necessarily that helpful.

Default Display

You can then get to the full class information by expanding the class, and you then will see a display similar to the following.

Full Info

This process becomes even more tedious when working with a collection or list of custom objects, with nesting that doesn't provide anything helpful.

List Debugging

What Can We Do?

Luckily there is a nice, easy way to get around this using an Attribute that is available in the System.Diagnostics namespace.  By adding a "using System.Diagnostics" statement to the top of our class, we can modify our class to include the DebuggerDisplay attribute, the completed "CustomerInfo" class is listed below.

[DebuggerDisplay("ID: {CustomerId}; FName: {FirstName}; LName: {LastName}")]
class CustomerInfo
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public bool Expired { get; set; }
}

With this attribute, we are able to setup a custom format string, the values included in curly-braces are substitutions for property values.  With this simple change, we now can see the following when debugging individual objects and lists.

Updated Individual Debugging

Updated List Debugging

Conclusion

I hope that this information has been helpful.  Feel free to share your comments below.

tags: .NET 2.0, .NET 3.5, C#
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.