The DebuggerDisplay Attribute
In an earlier article I described the use of the DebuggerDisplay attribute, explaining how the attribute can be used to alter the way that variable values are displayed in the debugger in areas such as the Locals and Autos windows. The article explained how the contents of the Value column in these windows could be controlled.
The DebuggerDisplay attribute provides some additional features with the use of named parameters. Two common such parameters are Name and Type. As their names suggest, these allow you to change the display of information in the Name and Type columns of debugger windows as well as in other areas.
Using the Name Parameter
We'll begin by considering the Name parameter of the DebuggerDisplay attribute. To see the effect that this gives, we need some sample code. Create a new console application and add the following class. NB: This class includes an automatically implemented property. If you are using an early version of the compiler you should expand this to a full property with backing store field.
[DebuggerDisplay("Dimensions={Dimensions}, Area={CalculateArea()}")]
public class Square
{
public int Dimensions { get; set; }
public int CalculateArea()
{
return Dimensions * Dimensions;
}
}
When creating an object of the Square type and viewing this in the Locals window, the DebuggerDisplay attribute causes the dimensions and area values to be shown, pictured below. The Name column shows the name assigned to the variable and the Type column shows the fully qualified name of the class.
Sometimes you will wish to change the information shown in the Name column of debugger windows. This can be achieved by adding a named parameter to the DebuggerDisplay attribute. The parameter is named, "Name", and receives a string value. The string can contain expressions, methods and property or field names using the same syntax as for the value.
[DebuggerDisplay("Dimensions={Dimensions}, Area={CalculateArea()}"
, Name="Square {Dimensions}")]
Using the above version of the attribute, the variable name in the Locals window shows the word "Square" and the value from the Dimensions property.
Adding the Type Attribute
Finally, you can change the text that appears in the Type column. Again, a named parameter is used and accepts a string that may contain references to fields and properties and expressions. The following attribute changes the Type displayed to suggest an instance of an "IShape" interface.
[DebuggerDisplay("Dimensions={Dimensions}
, Area={CalculateArea()}", Name="Square {Dimensions}", Type="IShape")]
5 June 2010