DebuggerDisplay attribute: Improve the debugging of collections

DebuggerDisplay attribute: Improve the debugging of collections

Consider the following Game example class:

    public class Game
    {
        public Guid Id { get; set; }

        public string Title { get; set; }

        public DateTimeOffset ReleaseDate { get; set; }

        public string Publisher { get; set; }
    }

Debugging a collection can be cumbersome. Especially when you need to open each item to find the correct object you’re looking for. In this case, we have a List of Game objects: Watch window without the DebuggerDisplay attribute

Adding a DebuggerDisplay attribute to our Game class can mitigate this issue. We can see at a glance which item is which. This saves us a lot of time compared to opening each item one by one. Watch window with the DebuggerDisplay attribute

All it takes to get this working is to add the DebuggerDisplay attribute to the class. In the case of our example Game class:

    [DebuggerDisplay("{Title, nq} - {ReleaseDate.ToString(\"dd-MM-yyy\")}")]
    public class Game
    {
        public Guid Id { get; set; }

        public string Title { get; set; }

        public DateTimeOffset ReleaseDate { get; set; }

        public string Publisher { get; set; }
    }

Same as with string interpolation you put the desired properties within curly braces, and this way it’s also possible to call methods on properties. Like the ToString method on the ReleaseDate property. You can also use format specifiers to further specify how values are to be displayed in the debugger windows. Like nq for not displaying quotation marks around a string.

It’s not perfect, when your label gets too complicated you’ll quickly get in trouble. For example, the quotation marks in the ToString method had to be escaped. When you want to start using conditional logic, it’s going to be a mess. In those cases, it is better to create a separate private method in your class, which you can call in the DebuggerDisplay attribute.