Make debugging collections (and not only) easier and tell debugger what to show. The DebuggerDisplay attribute comes to the rescue!
If you ever tried to find item on a list you can see only name of a class. It’s not really helpful.
What is DebuggerDisplay attribute?
The DebuggerDisplayAttribute controls how an object, property, or field is displayed in the debugger variable windows. This attribute can be applied to types, delegates, properties, fields, and assemblies. If applied to a base type, the attribute also applies to a subclass.
How to use DebuggerDisplay attribute?
I made console app. Lets create example class Book.
[DebuggerDisplay("{Id}", Name = "{Title}")] public class Book { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } public int Pages { get; set; } public Book(int id, string title, string author, int pages) { Id = id; Title = title; Author = author; Pages = pages; } } public class Books : List<Book> { }
Modify Main method at Program.cs
var books = new Books { new Book(0, "First", "A", 50), new Book(1, "Second", "B", 100), new Book(2, "Third", "C", 150), new Book(3, "Fourth", "D", 200), new Book(4, "Fifth", "E", 250), new Book(5, "Sixth", "F", 300), new Book(6, "Seventh", "G", 350), new Book(7, "Eighth", "H", 400), new Book(8, "Ninth", "I", 450), }; Console.WriteLine(books); Console.ReadKey();
With the attribute the debugger will display:
Lets modify the attribute.
[DebuggerDisplay("{Id} ({Pages})", Name = "{Title} / {Author}")]
Now debugger displays:
Now lets try to add the attribute to the Books class.
[DebuggerDisplay("{Count} books")] public class Books : List<Book> { }
The debugger will display:
DebuggerDisplay best practices
Don’t use multiple functions or properties in the display string
Each property / function needs to be evaluated individually and done so once for every instance of this type in every debugger display window. Imagine you have collection with thousands of this type. The evaluation needs to be done for EVERY instance. It might result in significantly decreased performance.
Don’t evaluate expressions that throw exceptions
Evaluating expressions is expensive. Evaluating expression with error is the worst scenario. Just don’t!
Don’t use mutating properties or functions
Don’t use expressions that will modify the underlying value. It leads to confusion.
Use private property to set attribute
[DebuggerDisplay("{DebuggerDisplay,nq}")] public class Book { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } public int Pages { get; set; } private string DebuggerDisplay { get { return $"{Id}: {Title} {Author}"; } } public Book(int id, string title, string author, int pages) { Id = id; Title = title; Author = author; Pages = pages; } }
The “,nq” means “no quotes” when displaying the final value.
Source code: DebuggerDisplay Demo