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:

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 replace the numbers with the property/method names you want to display.

Example:

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:

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.

Leave a Reply