In an effort to start blogging more about the "helpful" items that I have encountered over the years this is one of my first "Quick Tips" related to improving the life of the developer. We all have had those times where we are tracking down a complex problem within an application and all along the way we have to spend endless time mousing over individual classes to find out what their values are when most commonly we just want to know about one or two key values. Well in this post, I'll show you a neat trick using the "DebuggerDisplay" attribute to help make this process easier.

The Code


To get us started I'm going to just dive into the code, consider the following super condensed code sample.


   1:  static void Main(string[] args)
   2:  {
   3:      var badSampleInstance = new BadSample()
   4:                              { Name = "John Smith",
   5:                                  Address = "123 Main Street",
   6:                                  Phone = "515-555-1212" };
   7:      var goodSampleInstance = new GoodSample()
   8:                              { Name = "John Smith",
   9:                                  Address = "123 Main Street",
  10:                                  Phone = "515-555-1212" };
  11:      Console.ReadLine();
  12:  }
  13:   
  14:  public class BadSample
  15:  {
  16:      public string Name { get; set; }
  17:      public string Address { get; set; }
  18:      public string Phone { get; set; }
  19:  }
  20:   
  21:  [DebuggerDisplay("{Name} ({Phone})")]
  22:  public class GoodSample
  23:  {
  24:      public string Name { get; set; }
  25:      public string Address { get; set; }
  26:      public string Phone { get; set; }
  27:  }

From here we can see a very simple set of code with two classes. If you notice I have added an attribute "DebuggerDisplay" to the top of the GoodSample class. The value used for the display contains a few substitutions "{Name}" and "{Phone}". What this does is update all of the display areas in the debugger, that would typically show the type name for the value which isn't helpful to show the formatted value we supplied. An example of this can be seen here.




So as you can see this can help to get a good glance into your custom objects, and reduce a lot of the "mouseover" action that is common while debugging.


I hope that this content was helpful.