Skip to content

DebuggerDisplay for Better Debugging

Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.

Learn more about Software Architecture & Design.
Join thousands of developers getting weekly updates to increase your understanding of software architecture and design concepts.


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.
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.
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.

2 thoughts on “DebuggerDisplay for Better Debugging”

  1. Awesome post!

    Couple of tips:

    1. Little known fact about the DebuggerDisplayAttribute is that you can actually use it on 3rd part types (meaning classes you don’t have the source code for) – see http://stackoverflow.com/a/4475679/292555

    2. [Disclaimer: I’m the co-creator of the product I’m mentioning here] A bunch of years ago I got so frustrated with having to recompile my code every time I wanted to change the way an object is created in the debugger, that I created a commercial extension to Visual Studio (http://www.oz-code.com) that lets you do the equivalent of DebuggerDisplay dynamically at debug time – see https://www.youtube.com/watch?v=gg0hGWKOBoo

Leave a Reply

Your email address will not be published. Required fields are marked *