11 December 2013

[Debugger Display] attribute in C#.net explained

Today let's know one tip to make debugging the code is a lot easier using [DebuggerDisplay] attribute in C# .Net by going through below topics:

  1. Introduction to Debugger Display attribute
  2. Attributing classes with [Debugger Display] attribute
  3. [Debugger Display] attribute uses
  4. Debugger display attribute and coding standard

Introduction to Debugger Display attribute

The code is written once, where as code will be debugged and read many times. To understand the code sometimes we all debug it. Hence it's make life easier and improves developer productivity when debugging is made easy.

One such option to improve debugging is by using [DebuggerDisplay] attribute. Let's see how we can use the debugger display attribute to make debugging .net cod in visual studio easier.

Attributing classes with [Debugger Display] attribute

Let's consider the below employee class to understand debugger display attribute with an example.
[DebuggerDisplay("Id={Id}, Name={Name}, Department={DepartmentId}")]
public class Employee
{
  public string Id {get;set;}
  public string Name {get;set;}
  public Money Salary {get;set}
  public string DepartmentId{get;set;}
}

[Debugger Display] attribute uses:

Let's consider you are writing employee repository code, which possibly could look like below:

  Employee employee = Repository.Get("1234567");

While you debug, mouse over on the employee variable, you will get to see objects Id, Name & Department values like below. By looking at the values, we can easily decide whether the repository code is working as expected or not.

debugger display attribute

Without attributing debugger display attribute to classes, you have to use either the Immediate window or the Quick watch window, which takes one or more extra steps.

Debugger display attribute and coding standard

Now, we know the advantages of Debugger display attribute to enhance the debugging experience and make it easier. So it makes sense, to apply this attribute to classes for displaying key properties. Developer should always use the debugger display attribute while creating new entities, i.e. class, structures.

And also as part of the code review process the addition of new classes should be checked to see whether debugger display attribute is applied appropriately or not.

Having said this all, inclusion of applying Debugger Display to classes should be made part of the standard coding standard document.