I had to use a conditional break point recently, and I was very thankful for that feature. I thought it might be worth a quick post to spread the communal joy of conditional break points.

So, I’m assuming with the ideas of a break point. That is, clicking on the bar next to your code and adding a little red dot that will stop your code running (if your in debug mode) and let you take a closer look at what is going on. That’s a really useful feature.

Now suppose that you’re loading a file with 10,000 or so lines, and everything works as you expect it to for 4,000 lines, but then things start going wrong. Here’s an example of what the code might look like:

            string name, addressLine1, addressLine2, starSign;
uint age;

StreamReader reader = new StreamReader(@"D:\Files\files.txt");

name = reader.ReadLine();
addressLine1 = reader.ReadLine();
addressLine2 = reader.ReadLine();
starSign = reader.ReadLine();
if (!uint.TryParse(reader.ReadLine(), out age))
Console.WriteLine("Error parsing age value");


It would be really useful if you could stop the code at that point, and take a look at the data when it starts to go wrong, but if you slap a break point inside that while loop it’s going to get hit 4,000 times before you get to where you want to be.
This is a perfect example where you could use a conditional break point. If you right click on the break point you are presented with a menu of options.

Breakpoint right click menu

In this case, you could select Hit Count and the specify when you want the code to break it terms of how many times this breakpoint has been hit.

Stop when this line has been hit 4000 times

Another way of thinking of it would be that you want the break point to remain inactive for the first 3,999 times the code passes it, and then you want the code to stop so you can step through and see what is going on in more detail.
That’s really useful! but what are some of those other options? Might they be just as useful?

Stop if the name read in is Steve!

Well yeah, they are. Condition allows you to type a condition to break on, should it ever happen. In this case the code will break if the name read in is “Steve”.
When Hit allows you to instruct the compiler to do other things when the breakpoint is hit, such as print a message to the Output pane in visual studio – that means no more writing out to the console, assuming that there is a console to write out to!

when hit writer the name and two address lines to visual studio's output window

You can even combine different breakpoints, so for example I could write the addressLine1 value for all the entries with the name “Steve” to visual studios Output pane, it I wanted to:

Output Pane

It’s a very useful feature and if you’re not familiar with it already you should definitely check it out!