Sometimes the display and formatting of information in the Visual Studio debugger is less than optimal.
The DebuggerDisplay attribute allows us to customise how an object is portrayed in the debug window.
Imagine a Person object p with an AgeInYears and an Name property.
By default, in the debugger this would look like:
At the “root” level for the object we just get the type name.
If we override ToString() then we would get that output here instead.
If we want to override ToString() but have a different output at the root debug level we can apply the DebuggerDisplay attribute at the class level:
[DebuggerDisplay("This person is called {Name} and is {AgeInYears} years old")]
class PersonWithDebuggerDisplay
{
[DebuggerDisplay("{AgeInYears} years old")]
public int AgeInYears { get; set; }
public string Name { get; set; }
}
In the string we supply to the DebuggerDisplay attribute we can reference properties, fields, and methods in the class by wrapping them in {}.
This produces the following in the debugger:
Note that in the sample code above, the DebuggerDisplay attribute is also added to the AgeInYears property which produces the following when the object is expanded in the debugger:
The DebuggerDisplay attribute can be applied to:
- Classes
- Structs
- Delegates
- Enums
- Fields
- Properties
- Assemblies
While this is not something we’d use on every class as a matter of course, it may be helpful when we are doing a lot of debug work and we want to make life easier for ourselves. For more info on usage check out MSDN.
If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.
SHARE: