Debugging Tips - Part Two

Using DebuggerDisplay Attribute

While working on complex classes/objects, it really takes two more clicks to either add that object to the Watch window or expand the object in visualizer and navigate to a specific property.

To avoid these extra steps and to make your debugging bit faster, you can decorate the class with a specific property using DebuggerDisplay(using System.Diagnostics) attribute. Applying this attribute makes sure that when you add an object to the Watch window, it displays the value of above property in the Value column. This attribute has a string argument that takes in property/field name between curly braces (“{“&“}”) in string format.

This attribute is applicable to types, delegates, properties, fields, and assemblies.

For example, I have below Model class for which I am creating an object and list of objects with some dummy values. Also, I have decorated this class with DebuggerDisplay attribute that has a definition to display name of the person, ID of the person, and length of a name.

  1. /// <summary>  
  2. /// Debugger Display Attribute – Model class  
  3. /// </summary>  
  4. [DebuggerDisplay("Emp ID = {name} - {ID} - {name.Length}")]  
  5. public class TestDebuggerDisplay  
  6. {  
  7.     public string name  
  8.     {  
  9.       getset;  
  10.     }  
  11.     public int ID  
  12.     {  
  13.       getset;  
  14.     }  
  15. }  
Main Class
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.   
  6.         TestDebuggerDisplay obj = new TestDebuggerDisplay() { ID=1, name="name1" };  
  7.         List<TestDebuggerDisplay> lstObjs = new List<TestDebuggerDisplay>();  
  8.   
  9.         for (int i = 0; i < 5; i++)  
  10.         {  
  11.         lstObjs.Add(new TestDebuggerDisplay()  
  12.                 {  
  13.                 ID = 10 * (i + 1),  
  14.                 name = $"name{10 * (i + 1)}"  
  15.                 }  
  16.                 );  
  17.          }  
  18.             Console.WriteLine();  
  19.    }  
  20. }  
Output

While you are debugging, you will see that when the object is added to the Watch window, you can see the value for that object as below:

 
 

If you are looking for attributes that would help to make debugging, go more quickly please go through my other article on the same topic.

Please leave comments if you have question/suggestions.


Recommended Free Ebook
Similar Articles