by Brian Ensink
24. January 2009 22:09
In both small systems with a handful of functions and large systems with hundreds of types, collections, and complex object models the DebuggerDisplay attribute makes the debugging process easier by displaying more information in tooltips and debugging windows.
Consider a simple Circle class with X,Y, and Radius properties. Hover the mouse over the myCircle variable in the screenshot below and the tooltip displays as shown. This tooltip indicates that myCircle is a BE.Circle object but gives no other useful information. We can however expand the tooltip to display the values of the X,Y, and Radius properties and the private variables of the object.
The same thing is true in the Autos, Locals, and Watch debugging windows. Its not uncommon to expand through half a dozen or more levels of a complex object model. Its easy to lose one's place and become overwhelmed by the amount of information displayed.
Fortunately the DebuggerDisplay attribute can be used to display only the information most important for the given type. The Circle class with the attribute is shown in the code fragment below.
1: [System.Diagnostics.DebuggerDisplay("{GetType()} X={X}, Y={Y}, Radius={Radius}")]
2: internal class Circle
3: {
4: ...
The attribute defines a format string that is used to create the text shown in the tooltips and overrides the default text displayed by the debugger. In this case the text shows the object's type and the value of the X,Y, and Radius properties as shown below.
The DebuggerDisplay attribute can be applied to classes, structs, properties, fields, delegates and more. Use this attribute when defining classes to simplify inspecting variables and object models to make the debugging experience easier and more productive.