VisualStudio
 
By Firoz AnsariJune 11, 20192 min readComments (0)

Leslie Richardson on not so commonly used attribute DebuggerDisplay:

By writing DebuggerDisplay syntax at the top of a class, you can choose what strings and properties you want at the top of each object node in debugger windows. Besides displaying strings in debugger windows, adding curly brackets ({}) to the DebuggerDisplay attribute allows Visual Studio to display the value of a property or method that you specify.

I attempt to create a small console application below to follow the usage of DebuggerDisplay.

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

namespace ConsoleApp
{
  [DebuggerDisplay("{LastName}, {FirstName}")]
  public class Worker
  {
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Address { get; set; }
      public string City { get; set; }
      public string State { get; set; }
      public string Zip { get; set; }
      public string Phone { get; set; }
  }

  class Program
  {
      static void Main(string[] args)
      {
          List<Worker> workers = new List<Worker>();

          List<Worker> workers = new List<Worker>();
          workers.Add(
              new Worker {
                  FirstName = "Michael",
                  LastName = "Springer",
                  City = "Atlanta",
                  Phone = "001-232-1233"
              });
          workers.Add(
              new Worker {
                  FirstName = "Lloyd",
                  LastName = "Bever",
                  City = "Fort Myers",
                  Phone = ""
              });
          workers.Add(
              new Worker {
                  FirstName = "Vincent",
                  LastName = "Covey",
                  City = "Chester Heights",
                  Phone = "888-232-1233"
              });

          Console.WriteLine(workers.Count);
          Console.ReadKey();
      }
  }
}

QuickWatch - Without DebuggerDisplay

QuickWatch - With DebuggerDisplay

You can also use nq (no quote) specifier if you don’t prefer to see quotes in debug values.

  [DebuggerDisplay("{LastName, nq}, {FirstName, nq}")]
  public class Worker
  {
    //...
  }
}

QuickWatch - DebuggerDisplay with No Quote Specifier

You can further extend DebuggerDisplay if you want to include an expression in debug values. Just add a private method or property in the target class, and provide that method or property to DebuggerDisplay.

[DebuggerDisplay("{DebuggerString(), nq}")]
public class Worker
{
  private string DebuggerString()
  {
      return string.Format($"{FirstName}, {LastName}. Has Phone: {!Phone.Equals(string.Empty)}");
  }
  //...
}

QuickWatch - DebuggerDisplay using Expression

JOIN THE DISCUSSION
COMMENTS (0)