Skip to content

DebuggerDisplay for Better Debugging

DebuggerDisplayJust wanted to make a quick post about a long forgotten friend the DebuggerDisplay attribute.

The DebuggerDisplayAttribute Class controls how an object, property, or field is displayed in the debugger variable windows. This attribute can be applied to types, delegates, properties, fields, and assemblies.

The DebuggerDisplay attribute has a single argument, which is a string to be displayed in the value column for instances of the type. This string can contain braces ({ and }). Text within a pair of braces is evaluated as a field, property or method.

Example

So here I’m going to have a Person class.  I’m going to define the attribute to show the firstname and lastname.

using System.Diagnostics;
namespace DebuggerDisplay
{
class Program
{
static void Main(string[] args)
{
var person = new Person("Derek", "Comartin", "derek@codeopinion.com", "codeopinion");
}
}
[DebuggerDisplay("{Firstname} {Lastname}")]
public class Person
{
public string Firstname { get; }
public string Lastname { get; }
public string Email { get; set; }
public string Twitter { get; set; }
public Person(string firstname, string lastname, string email, string twitter)
{
Firstname = firstname;
Lastname = lastname;
Email = email;
Twitter = twitter;
}
}
}

Now when we debug, this is the result when we look at the new person instance.

DebuggerDisplay

Best Practice?

In most open source projects, it appears one of the practices many employ is creating an internal DebuggerDisplay that returns the relevant string you want to display.

using System.Diagnostics;
namespace DebuggerDisplay
{
class Program
{
static void Main(string[] args)
{
var person = new Person("Derek", "Comartin", "derek@codeopinion.com", "codeopinion");
}
}
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Person
{
public string Firstname { get; }
public string Lastname { get; }
public string Email { get; }
public string Twitter { get; }
internal string DebuggerDisplay => $"{Firstname} {Lastname}";
public Person(string firstname, string lastname, string email, string twitter)
{
Firstname = firstname;
Lastname = lastname;
Email = email;
Twitter = twitter;
}
}
}

Notice the “nq” in the DebuggerDisplay Attribute, this is to simply say “No Quotes”.  Here is the resulting output:

DebuggerDisplay

More

There are so many things like this attribute that either we just don’t know about or forget about along the way.  If you have any other suggestions please leave a comment here or on twitter.