Last week, we started to explore the first of the Debugger attributes that are found in the System.Diagnostics namespace by looking at the DebuggerBrowsable attribute. I’d like to continue that theme this week with the DebuggerDisplay attribute.

No doubt you’ve seen that hovering your mouse over a variable while you are in Break mode will cause a tooltip to be displayed, which shows the type of object you are hovering over. You can see this below, where the datatip for a Customer object is shown.

Customer class with a default datatip

Unfortunately this information is not particularly useful, as most of the time you have a fairly good idea about the type of object you are dealing with. It would be better for this single line to contain more useful information about the object, as is the case with simple types such as strings or integers where the actual value is displayed.

This is where the DebuggerDisplay attribute comes in handy. It can be used to change this single line representation of the object from the default full class name. The attribute takes a single parameter, which is a String. The format of this string can include the { and } braces, which can contain a field, property, or method that returns a value.

For example, you could apply the DebuggerDisplay attribute to the Customer class as follows:

[DebuggerDisplay("Customer {CustomerName} has {Orders.Count} orders")]
public class Customer

If you apply the attribute in this way, it will result in the following datatip:

Customer class with DebuggerDisplay attribute

If you are a C# developer, then in addition to specifying properties and methods in the DebuggerDisplay format string, you can also include a general expression within the braces. For example, the following attribute shows how you could use an expression with a ternary operator:

[DebuggerDisplay("Customer {CustomerName} has orders? {(Orders.Count > 0) ? \"Yes\" : \"No\"}")]

Which would result in the following datatip:

Customer class showing datatip with DebuggerDisplay attribute expression

One final thing to note, in addition to Classes, the DebuggerDisplay attribute can be applied to any Struct, Delegate, Enumeration, Field, Property, or even an entire Assembly.