Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

When debugging your C# code Visual Studio will by default display the classname, including the namespace, of an object, for example in the watch window or when hovering your mouse over the name of the object. This is pretty useless and it would be much more useful if it would display the contents of some key properties of the object. Fortunately this can be achieved by using the DebuggerDisplay attribute.

Suppose we have defined the following class called Company:

namespace ConsoleApp
{
    class Company
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string PhoneNumber { get; set; }
    }
}

And suppose we have written the following small test console application:

class Program
{
    static void Main(string[] args)
    {
        Company company = new Company();

        company.ID = Guid.NewGuid();
        company.Name = "Test company";
        company.Address = "Test address";
        company.PhoneNumber = "1234-56789";

        Console.WriteLine("The current company is {0}.", company.Name);
    }
}

When we run this in debug mode, set a breakpoint on the last line and hover our mouse over the variable company we will see that the classname, including the namespace, is displayed:

Default behavior

Default behavior

This is pretty useless. We would rather see the contents of the properties ID and Name. To achieve this we add the DebuggerDisplay attribute to the class Company with the displaystring "ID={ID}, Name={Name}":

namespace ConsoleApp
{
    [DebuggerDisplay("ID={ID}, Name={Name}")]
    class Company
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string PhoneNumber { get; set; }
    }
}

Now when we run this again in debug mode and hover our mouse over the variable company we will see the following:

Display with DebuggerDisplay

Display with DebuggerDisplay

If you prefer a less technical display, you can for example replace the display string of the DebuggerDisplay attribute by the following:

[DebuggerDisplay("The ID is {ID} and the Name is {Name}")]

In debug mode this results in the following display:

Less technical display with DebuggerDisplay

Less technical display with DebuggerDisplay

In the last example the property Name is displayed surrounded by double quotes. If you do not like this, you can suppress the double quotes by adding the option nq to the property Name within the display string of the DebuggerDisplay attribute:

[DebuggerDisplay("The ID is {ID} and the Name is {Name, nq}")]

This results in the following display:
Less technical display with quotes with DebuggerDisplay

Less technical display with quotes with DebuggerDisplay


 © Evident Interactive BV