Debugger tips VS.Net… DebuggerDisplayAttribute and overriding ToString()

In this post I want describe the manners in which Visual Studio.Net shows information of object instances in the several variable debugger windows; the Autos, Local and Watch windows. To support the post I have placed images of the source code and several variable debugger windows at the end of the article.

Normally Visual Studio.Net shows variables in the debugger windows as a node representing the type with only the type name in the Value column (see below). This can be useful but in general you want more information about the value of the attributes of the class. Especially if the node is folded. Fortunately, the. NET framework gives a developer an opportunity to manipulate the information shown contained in the Value column. This can be done by overriding the ToString() method of a class or by annotating the class with the DebuggerDisplayAttribute.

Visual Studio.Net uses the ToString() method to fill the Value column. Hence, the type is shown. By overriding the ToString() method a developer can change the value in the Value column. Look for an example at the images below.

A developer can use the DebuggerDisplayAttribute when overriding the ToString() method is not suitable. As you can see in the code the DebuggerDisplayAttribute accepts a string which indicates how and what data should be shown. In the string can contain the {} braces. The text between the braces is evaluated to a field, property or method. Locals, pointers and aliases can not stand between the braces.

The DebuggerDisplayAttribute can be used on:

  • Classes,

  • Structures,

  • Delegates,

  • Enumerations,

  • Fields,

  • Properties,

  • Assemblies.

The Type property can be left blank if no type information is required to be shown. The Name property can contain the string that indicates information that should be shown: the string with the {} braces. The Target is used to register the type on which the attribute applies when it is defined at assembly level.

kick it on DotNetKicks.com

 

The code:
 
 
 The standard view
 
The view with ToString() overridden
 
The view with the DebuggerDisplayAttribute