Blog Post

Debugging classes made easier using DebuggerDisplay

Wednesday, July 15, 2015 3:13 PM

THE DEBUGGERDISPLAY ATTRIBUTE

This tip may not save the day like the previous two, however, it will save a lot of time in debugging things like lists and arrays of objects that are alike but have different values.

Let’s say you are trying to debug a list of phone numbers and know the one it is failing on but don’t know where in the list it is.  This can be a challenge when the list gets long and looks like the following:

Debug2

In the past, I’ve overridden the ToString() method to print out the phone number (or pick your properties for your class).  This may not be an option if the code actually uses the ToString() method for your class.  Thankfully, starting in .NET Framework 2.0, you can use the DebuggerDisplay attribute on the class.  It is used to display whatever you would like when inspecting something in the debugger.  The attribute can be applied to the following:  class, structure, delegate, enumeration, field, property, assembly.

DECORATE THE PHONE CLASS AS FOLLOWS:

 

[DebuggerDisplay("({AreaCode, nq}) {Prefix, nq}-{LineNumber, nq}")]
public class Phone
{
    public string AreaCode { get; set; }
    public string Prefix { get; set; }
    public string LineNumber { get; set; }

The ‘nq’ stands for ‘no quotes’ since by default the properties that are evaluated within the brackets are surrounded by double-quotes.

Now, the debugger looks better when we inspect this list:

Debug3



To find out about debugger display attribute use this link to msdn