Wednesday, March 12, 2014

Customizing debugging session - Part I

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 particular property or let’s say very few properties of a huge object and it gets TIMEOUT. Uhhh !!!

This time, we feel like there should be some easy way to navigate to that particular property instead of going to the object and clicking on plus symbol to reach the required property. Well, let’s understand it via code:

Aim: I have an Employee class with two members as 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 below screen:







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







Now first question is, is there any way to display customized message in debugger window? Answer would be YES. One simple override method will do this job for us.

Let’s go ahead and override the ToString method as shown below:












Now launch the application and you will be able to view your text during debugging as shown below:







Point to understand here is, by default Visual Studio uses 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 click on plus symbol in debugger window, you will still be able to view employee’s branch and name.

Well, it’s time to move for next question which I feel is very important concept.
Second question is, is there any way to display value of required property instead of customized message? Again answer is a big YES. A simple attribute named DebuggerDisplay will rescue you.

Let’s quickly jump on the code to check, how to use this attribute:






As you can see that the attribute can be applied to 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 time to see, what debugger will show us:






Isn’t it a cool feature? 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 properties level, if your properties are complex and less self-explanatory. Enjoy debugging!!!



No comments:

Post a Comment