Skip to main content

Command Palette

Search for a command to run...

A Guide to Using DebuggerDisplay Attribute for Better Debugging

Published
1 min read
A

developer from India who is passionate about cloud and .Net

The DebuggerDisplayAttribute helps provide meaningful information about complex objects while debugging the application. Consider the following example where we set a breakpoint on the productList. In order to view the difference, comment out DebuggerDisplayAttribute and see what data we are viewing in the debugger window. we can see a list of products, but the details are not immediately visible, requiring us to expand each complex object to view its properties.

using System;
using System.Collections.Generic;
using System.Diagnostics;

[DebuggerDisplay("Product name - {Name} and Product id - {Id}")]
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var products = new List<Product>()
        {
            new Product { Id = 1,Name="Product 1", Description="Product1 descriptio"},
            new Product { Id = 2,Name="Product 2", Description="Product2 descriptio"},
            new Product { Id = 3,Name="Product 3", Description="Product3 descriptio"},
            new Product { Id = 4,Name="Product 4", Description="Product4 descriptio"},
            new Product { Id = 5,Name="Product 5", Description="Product5 descriptio"}
        };
        var productsList = products;        
        Console.WriteLine($"{productsList.Count}");
    }
}

Remove commented code and see the difference.

This technique is really useful when i was debugging some complex objects.

K

Nice! I was wondering how I can do that, but it was not crucial so I didn't find time to look for that. Nice that I found this article accidentally