Visual Studio – How to use conditional breakpoints

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.
Visual Studio - Hovering over a Breakpoint (little red circle), showing the Settings 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.
Visual Studio - Conditional breakpoint options - Conditions checked and conditional expression set (coder.Language == "C#")
  • Run the debugger and wait for it to hit the breakpoint.
Visual Studio - Debugger pausing execution on conditional breakpoint because conditions were met (coder.Language == "C#")

Notice that it only breaks when the breakpoint condition is met (coder.Language == “C#”).

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:

Visual Studio - Conditional breakpoint when Hit Count == 3

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:

Visual Studio - Breakpoint configuration with Action checked. It'll output "Coder {coder.Name} {coder.Language}" to the Debug output window.

Now when you run the debugger and hit the breakpoint, it’ll show the messages in the Debug output (Output window > Debug option):

Visual Studio - Showing Breakpoint debug messages

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.

Leave a Comment