Home > .Net Technologies, C#/VB.Net, CodeProject, Dot Net Tips > Using DebuggerDisplayAttribute

Using DebuggerDisplayAttribute

In .Net, we can view variables contents in different ways like local window, quick watch, etc. In System.Diagnostics namespace, we can see a DebuggerDisplayAttribute class that is used to view variables’ contents in debugger window. This attribute can be applied to class, field, property, enum, delegate, struct, etc.  Using this attribute, we can easily view variable contents in debug mode, and those contents are easily visible as data tip when we move mouse pointer over that variable. This attribute becomes quite useful when we have to view inner contents of custom type object variable when it has collection of values.

For example, we will apply this attribute to a class and watch the collection values in debug window.

[DebuggerDisplay(“Client Name = {CustomerName} Client Type = {CustomerType, nq}”)]
class Customer
{
private string _CustomerName;
private string _CustomerType;
public Customer(string strCustomerName, string strCustomerType)
{
_CustomerName = strCustomerName;
_CustomerType = strCustomerType;
}
public string CustomerName
{
get { return _CustomerName; }
}
public string CustomerType
{
get { return _CustomerType; }
}
}
Now after loading a Customer type collection, we see following view in data tip:
DebuggerDisplayAttribute

Fig 1: DebuggerDisplayAttribute changing the data view.
Had not we used DebuggerDisplayAttribute on Customer class type, we would have to traverse a long hierarchy of tree view of each index value of collection object to view data contents.

Programmers often override ToString() method in the custom class type method to view data. But still DebuggerDisplayAttribute wins the heart!

When ToString() method is overridden inside Customer class, then ToString() method of Customer object will result as:

public new string ToString()
{
return (“Customer Name: ” + _CustomerName + “\n” + “Customer Type: ” + _CustomerType);
}
ToString Method
Fig 2: Result of overridden ToString() method.

DebuggerDisplayAttribute constructor has only one parameter as string. The {} braces contain field or property or method name. In the example above, we have used this way.

[DebuggerDisplay(“Client Name = {CustomerName} Client Type = {CustomerType, nq}”)]

One can also quickly see {CustomerType, nq}. Due to this “nq” specifier, Client Type value is shown without double quotes, whereas Client Name value is still in double quote (see Fig 1). The “nq” specifier is used for string type properties.

Happy debugging for next time!

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment