Breakpoints cause execution to pause when you’re running the debugger. This is referred to as breaking, and it allows you to look at the current state of things for debugging purposes. In some cases, you may want to use a conditional breakpoint to only break execution when certain conditions are met (ex: break when name == “Bob”).
Here’s how to add a conditional breakpoint:
- Add a breakpoint (by clicking to the left of the line numbers -or- right-click > Breakpoints > Insert Breakpoint).
- Hover over the breakpoint and click the Settings gear button.
Note: In newer versions of VS, you can right-click and directly pick “Insert conditional breakpoint.”
This will show breakpoint configuration options.
- Tick the Conditions checkbox.
- Write a conditional expression (ex: coder.Language == “C#”).
- Click Close.
- Run the debugger and wait for it to hit the breakpoint.
Notice that it only breaks when the breakpoint condition is met (coder.Language == “C#”).
Table of Contents
Break on hit count
Sometimes it makes sense to break execution when a breakpoint has been hit a certain number of times. For example, let’s say you want to break on the third iteration of a loop. To do that, you can use the Hit Count condition, like this:
Now when you run the debugger, it’ll break execution when this breakpoint is hit for the third time.
Use breakpoint to print out debugging messages
Printing out debugging messages can help pinpoint where a problem is happening. Usually you’ll add print statements all over the place, and then have to delete them once you’ve figured out the problem. One way to print out debugging statements without modifying your code is by configuring breakpoints (conditional or not) with the “Show a message in the Output Window” action, like this:
Now when you run the debugger and hit the breakpoint, it’ll show the messages in the Debug output (Output window > Debug option):
Note: The Continue code execution setting means it won’t break execution when the breakpoint is hit. Instead, it will just print out the debugging message. This is usually what you want when you’re using breakpoints for printing out debug messages.