Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Using DebuggerDisplayAttribute

5.00/5 (6 votes)
12 Oct 2010CPOL2 min read 19.1K  
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 a collection of values.

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

C#
[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 the following view in data tip:

DebuggerDisplayAttribute

Fig 1: DebuggerDisplayAttribute changing the data view.

Had we not used DebuggerDisplayAttribute on Customer class type, we would have to traverse a long hierarchy of tree view of each index value of collection objects 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:

C#
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.

C#
[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!


Posted in .NET Technologies, C#/VB.NET, CodeProject, Dot NET Tips Tagged: .NET 3.5, C#, Debugging

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)