
.NET 2.0+Using the DebuggerDisplay Attribute
When debugging, the contents of strings and numeric types can be viewed in the locals and watches windows. When a custom object is displayed, the name of the class or the result of ToString() is shown. This can be changed with a DebuggerDisplay attribute.
The DebuggerDisplay Attribute
When using the Visual Studio debugger to execute a program in debug mode, you can view the contents of variables in various manners, including using the locals window and by adding watches. When a variable contains an object, it is generally displayed using a tree structure. When the branches of this tree are expanded, you can see all of the properties and fields of the object. However, the initial view of the variable can be less useful. If the class does not override the ToString method, only the name of the object's type is displayed. If ToString is overridden, the result of executing this method is shown.
If you wish to show more meaningful information for a class' instances whilst debugging, you may decide to override ToString, as would be required in the .NET framework version 1.1. However, this is not a viable solution if you need to use this method for other purposes. With the .NET framework version 2.0 and later, you can apply the DebuggerDisplay attribute instead.
The DebuggerDisplay attribute can be added to a class, structure or many other elements of your code. The attribute includes a single argument that is supplied as a string. This string is displayed in debugger windows instead of the object's class name or the results of the ToString method. The string can contain references to fields, properties and methods in the class so that the actual values from an object may be included in its description. It may also include simple expressions.
Adding the DebuggerDisplay Attribute to a Class
To demonstrate the use of the DebuggerDisplay attribute we need a simple class. The class will represent a square with a property for the dimensions of the shape and a method that calculates the area. Create a new console application and add the following class to it. In this case, the property is expressed using C# 3.0 automatically implemented property syntax. If you are using an earlier version of the .NET framework, expand this to include a full property definition with a backing variable.
public class Square
{
public int Dimensions { get; set; }
public int CalculateArea()
{
return Dimensions * Dimensions;
}
}
To create an instance of the class, add the following code to the Main menu of the Program class in the console application:
Square s = new Square();
s.Dimensions = 5;
We can see the output of the object in the debugger by stepping through the code until the Dimensions property has been set. The locals window shows only the name of the class for the object until expanded.

10 March 2009