Debugging, love it or hate it! Debugging is a skill that you won’t learn by reading a book but a skill that you perfect through practice (cliche, am I right?). It also makes you think outside the box in order to understand the issue better. Having said that I am guilty of finding a technique and sticking with it without being aware that there are better ways. Well recently I discovered a feature in Visual Studio that is efficient and helpful. I’m talking about breakpoint actions and tracepoints. What really blew my mind is that this feature has been around for quite a few years now (hence why I said I’ll stick with a technique) but for some reason I never really discovered it or used its full potential. Consider the following program, very straight forward but with long iterations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var status = ""; | |
for (int i = 0; i < 1000; i++) | |
{ | |
if (i < 100) | |
{ | |
status = "first hundred"; | |
} | |
else if (i < 200) | |
{ | |
status = "second hundred"; | |
} | |
else if (i < 300) | |
{ | |
status = "third hundred"; | |
} | |
else if (i < 1000) | |
{ | |
status = "the rest"; | |
} | |
} | |
System.Diagnostics.Debug.WriteLine("end of loop"); | |
Console.ReadLine(); | |
} | |
} |
Breakpoint actions
First thing we want to debug, and are interested in, is to know what the value of the iterator i is every time the value of the variable status changed. In that case we would set up a break point like below. Instead of stopping execution I decided to output the value of i in the output window.
Another approach, given that we are looping for a thousand times, would be to stop, or output a value, when the iteration hits a specific point. In my case when the value of i is equal to 567, and again I decided to output the value of status in the output window using string interpolation.
Writing values in the output window
Sometimes you might not be interested in stopping the execution of the program, and in that case using the output window is a good way to analyse the values of your variables. Simply add the following snippet to any point in your source code where execution is happening and you should be able to see the results in your Visual Studio output window. Be sure to have Debug selected in the drop-down list.
System.Diagnostics.Debug.WriteLine("hard coded string or " + yourVariable);
Results
After setting all your breakpoints with specific conditions, you are now ready to run the program. The outcome should be similar to the the following.
That’s me done debugging for the day, hope you found this post helpful and see you in the next post.
Bjorn