Customizing Debugging Session in .NET: Part I

(The source code is attached.)

I hope, being a developer everyone needs to debug their code at least once a day even if it is a very small snippet. Frankly speaking, sometimes it becomes very frustrating when we are looking for a value of a specific property or let's say a very few properties of a huge object and it times out
 
This time, we feel like there should be some easy way to navigate to that specific property instead of going to the object and clicking on the plus symbol to reach the required property. Well, let's understand it via code.

Requirement: I have an Employee class with two members, EmployeeName and BranchName. I want to know the name and branch of an Employee during my debugging session. So, I start debugging and lend up on the following screen:

Employee class
 

 Now in order to view the required details, I need to expand the employee object as shown in the following screenshot:
 
employee object 

 
Now the first question is:

Is there a way to display a customized message in the debugger window?

The answer is yes. One simple override method will do this for us.

Let's proceed to and override the ToString method as shown below:
 
ToString method 
 
Now launch the application and you will be able to view your text during debugging as shown below:
 
debugging 

 
The point to understand here is, by default Visual Studio uses the ToString method in the debugger. Please note, overriding the method will only display the message and it won't affect the values of your employee object. In other words, on the click of the plus symbol in the debugger window, you will still be able to view an employee's branch and name.
 
Well, it's time to move to the next question that I feel is a very important concept.
 
The second question is:

Is there a way to display the value of required property instead of customized message?

Again the answer is a big yes. A simple attribute named DebuggerDisplay will rescue you.

Let's quickly get to the code to check how to use this attribute:

 
attribute 
 
 As you can see that the attribute can be applied to the class level and takes a string as a parameter and inside the string, one can reference the member variables of the class using curly braces. Now it is time to see what the debugger will show us:
 
debugger 
 
 Isn't it a cool feature? I hope you will use it :)
 
 One can use this DebuggerDisplay attribute with classes, enums, delegates, structs, fields, properties as well as with assemblies.
 
 When to use this DebuggerDisplay attribute?
 

 One certainly can't use it all the time due to its maintenance overhead. I would recommend it to be used at class level and can be at the properties level, if your properties are complex and less self-explanatory. Enjoy debugging!!!

Up Next
    Ebook Download
    View all
    Learn
    View all