Use the DebuggerDisplay attribute to aid your Visual Studio debugging

Posted: (EET/GMT+2)

 

When you are debugging, being able to monitor or watch variable values is often instrumental in finding your bugs. In this job, the Watch and Local windows are really helpful, but sometimes they require too many mouse clicks to reveal those object property values that you need. This is especially true if you have lots of custom classes whose key properties you want to see quickly.

By default, the Value column of the, say, Locals window displays the type (class) name of a class instance variable. So, to view the property values of that class, you need to expand the class with the small plus sign on the left of the variable name. This is trivial of course, but an additional step that you need to make each time. Wouldn't it be great if you could specify how Visual Studio should visualize your class values?

Luckily, this is why the DebuggerDisplay attribute in the System.Diagnostics namespace was created in the first place. To use it, you would pass in a string with property names in brackets, and at runtime (debug time) Visual Studio would display the values there.

For example:

[DebuggerDisplay("ID = {CustomerID}, Name = {Name}")]
public class CustomerInformation
{
  public int CustomerID { get; set; }
  public string Name { get; set; }
  public string Address { get; set; }
  public string City { get; set; }
  public string Country { get; set; }
}

After this, the Locals window would display the class instance as a string like "ID = 123, Name = John" like this:

Of course, you can still expand the class to see all the properties, but by using DebuggerDisplay attribute you won't need to do that anymore for most cases. Simple and neat.