DebuggerDisplay in C# comes handy when debugging

One thing a developer does all the time is debugging code, very obvious. At times the value of property or output of a method you are interested in might be deep inside a class.

While debugging you would frequently add them to quick watch window or pin (bookmark) them to reach out quickly.

One productivity tip is that you can use DebuggerDisplay on entities to make it quickly accessible while debugging.

Let's take a simple class as example:

namespace DebuggerDisplaySample
{
    using System;
    using System.Diagnostics;
    using System.Globalization;

    public class Program
    {
        public static void Main(string[] args)
        {
            var programInstance = new Program();
            programInstance.LastSavedDateTime = DateTime.ParseExact(
                "21-05-1985 12:12 PM",
                "dd-MM-yyyy hh:mm tt",
                CultureInfo.InvariantCulture,
                DateTimeStyles.None);
            Console.ReadLine();
        }

        public DateTime LastSavedDateTime { get; set; }
    }
}

Here when you debug and hover on the programInstance or pin it (bookmark) it will show you the full name of the class as DebuggerDisplaySample.Program.

To access the LastSavedDateTime value you will have to expand the object further.

DebuggerDisplay - Before

Now add DebuggerDisplay attribute from System.Diagnostics on the Program class to see the change:

namespace DebuggerDisplaySample
{
    using System;
    using System.Diagnostics;
    using System.Globalization;

    [DebuggerDisplay("{LastSavedDateTime}")]
    public class Program
    {
        public static void Main(string[] args)
        {
            var programInstance = new Program();
            programInstance.LastSavedDateTime = DateTime.ParseExact(
                "21-05-1985 12:12 PM",
                "dd-MM-yyyy hh:mm tt",
                CultureInfo.InvariantCulture,
                DateTimeStyles.None);
            Console.ReadLine();
        }

        public DateTime LastSavedDateTime { get; set; }
    }
}

For attribute input we have passed {LastSavedDateTime} which is a property in program class. The { braces indicates the runtime to fetch the value of property named LastSavedDateTime and display it instead of the class name (which is debugging default behavior).

After doing this when you run and debug, you will see the value of LastSavedDateTime property on hover or pinning of programInstance variable.

DebuggerDisplay - After

This is not only limited to class and / or properties - refer MSDN to find out more ways to optimize your debugging time.

Happy coding !!