Customising the Appearance of Debug Information in Visual Studio with the DebuggerDisplay Attribute

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:

image

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:

image

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:

image

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:

New Pluralsight Course: C# Tips and Traps

My latest Pluralsight course: C# Tips and Traps is now live.

It’s a collection of things to:  “Short-circuit your learning of C# with this smorgasbord of handy C# and .NET features.”

It's sometimes hard to know what you don't know

Description: Whether you're still learning C# or you already have some experience, it's sometimes hard to know what you don't know. This course is designed to short-circuit your C# learning and provides a whole host of useful information about the sometimes under-used or unknown features of both the C# language and the .Net framework. It's suitable for those who are brand new to C# as well as experienced developers looking to "round off" their C# skills and "fill in the gaps".

You can watch C# Tips and Traps Pluralsight course now, also if you have a Plus level subscription you can also get access to all the demo code exercise files used in the course and play around with the things yourself.

SHARE: