DebuggerDisplay Attribute

Have you ever tried to debug an application and wish the Visual Studio debugger did not display {Namespace.ObjectName} when you wanted to see some of the details of the objects?

image

Visual Studio has an attribute that you can add to a class to inform the debugger what to display when it is displaying that class in the debugger. As you probably guessed the attribute is called DebuggerDisplay.

How to Implement

Let’s say we have a simple class called Person, the Person class has 4 properties; FirstName, MiddleName, LastName and FullName. Here is the definition:

public class Person
{
	public string FirstName { get; set; }
	public string MiddleName { get; set; }
	public string LastName { get; set; }    
	public string FullName
  	{
    	get
		{
			return string.Format("{0} {1}{2}", 
				FirstName, 
				(string.IsNullOrEmpty(MiddleName)) ? string.Empty : MiddleName + " ", 
				LastName);
    	}
	}
}

Next, let’s assume we want to display the first and last name of the person when debugging. We first need to add the DebuggerDisplay attribute to our class. The DebuggerDisplay attribute can be found in the System.Diagnosis class of the .NET framework. The DebuggerDisplay works almost like the string.Format method, except you replace the numbers with the property / method names you want to display.

Example:

[DebuggerDisplay("FirstName={FirstName} LastName={LastName}")]

This will tell the debugger to display the string FirstName= with the value of the FirstName field in double quotes followed by LastName= with the value of the LastName field in double quotes every time it needs to display a person object. Here is our new class:

[DebuggerDisplay("FirstName={FirstName} LastName={LastName}")]
public class Person
{
  public string FirstName { get; set; }
  public string MiddleName { get; set; }
  public string LastName { get; set; }    
  public string FullName
  {
    get
    {
      return string.Format("{0} {1}{2}", FirstName,
          (string.IsNullOrEmpty(MiddleName)) ? string.Empty : MiddleName + "", 
          LastName);
    }
  }
}

This will display like so:

image

You’ll notice this makes it easier to see what you are looking at. It also works in the immediate window.

image

Summary

You can use more than just field names. Method calls can be done (although probably not the best) and some calculations. Take a look at the MSDN documentation for the DebuggerDisplay attribute for more information.

There is also an article titled DebuggerDisplay attribute best practices that you should read also.

%d bloggers like this: