Debugger Display Attribute In Visual Studio

Before I start explaining what is DebuggerDisplay attribute, let me describe the problem description.

Let’s say you have a Person class having a complex structure. As a developer, while debugging you like to know which instance of Person class is used in a class.

One way of finding the required information, however complex, is to look in to the object tree in the debugger dialogue box.

quickwatch

What if we just want to know the value of Name property of the instance on mouse hovering on the person instance?

Well, technically, what is shown as a value next to person is the return value from toString() method that returns the name of the type (Person in this case). As a developer you could have overridden toString() method and return the property name of the instance. But doing so, would affect both Debug and Release builds and of course as a developer you would not want it.

To the rescue comes the DebuggerDispay attribute from System.Diagnostic namespace.

The DebuggerDisplayAttribute (System.Diagnostics.DebuggerDisplayAttribute) controls how a class or field is displayed in the debugger variable window. DebuggerDisplay attribute class has several overloads. Let’s look at them one by one. But before we delve into it, let us first see how can we achieve the required behavior from our problem description.

  1. [DebuggerDisplay("Name")]  
  2. public class Person  
  3. {  
  4.     public string Name;  
  5.     public List < Addres > AddressList = new List < Addres > ();  
  6. }  
Instance
  1. Person person = new Person()  
  2. {  
  3.     Name = ”James”  
  4. };  
Output

Output

Oops, we got only the “Name” as a string passed to DisplayDebugger in the debugger window; why not instance Name value as “James”. The answer is you got what you passed in to DisplayDebugger.

In order to get the value of Name field / property of the instance, you should pass the field / Property name within curly braces “{Name}”.
  1. [DebuggerDisplay("{Name}")]  
  2. public class Person  
  3. {  
  4.     public string Name;  
  5.     public List < Address > AddressList = new List < Address > ();  
  6. }  
Don’ts: Writing as [DebuggerDisplay(“{Person.Name}”) to access a property or a field, would throw an error in debugger dialog (shown below).

expressions

Another variant from DebuggerDisplay is to call a function to display string value in debugger dialogue window.

[DebuggerDisplay("Display String value is {DisplayString()}")].

Output:

Display String value is [7, 8, 9]

To summarise, the DebuggerDisplay controls how a class or field is displayed in the debugger variable windows. This attribute can be applied to:
  • Classes
  • Structs
  • Delegates
  • Enums
  • Fields
  • Properties
  • Assemblies

For more information. Please refer to Microsoft documentation (link below):