Conditional breakpoint in Visual Studio

Conditional breakpoint in Visual Studio

Debugging is an important part of software development as well as to identify issues in code. But many times we want the breakpoint set to hit directly at the condition we want. For example, suppose in a loop running from 0 to 100, we know that the code breaks when the index is 90, now generally we will set the breakpoint and then click on continue debugging 89 times till we achieve the index 90, now this is complete waste of time and effort as we know that till index 89, the code works fine, this is where conditional breakpoint plays a huge role. We can set conditions on the breakpoint and the breakpoint would be hit only when the condition is met.

To set the conditional breakpoint,

First set the breakpoint on the line which you want to debug by clicking in the left margin of a source code file, or by putting your cursor on a line of code and pressing F9.

setting-breakpoint-1.png

Now right-click on the breakpoint and choose Conditions from the context menu to get the Breakpoint Settings window. Alternatively, you could hover over the breakpoint and choose the settings icon.

conditions1-1.png

conditional-breakpoint-1.png

When you check the Conditions box, the window expands to show the different kinds of conditions. When you select Conditional Expression, you can then choose two conditions: Is true and When changed. Choose Is true if you want to break when the expression is satisfied, or choose When changed if you want to break when the value of the expression has changed. In this blog, we will choose Is True and set the condition as

i == 90

The conditions need not necessarily be a simple one, they can be a complex LINQ query as well, it all depends on what condition you want the breakpoint to be hit. Click on Close once you are done with the query.

conditional-breakpoint-set-1.png

Notice that the red dot in the left margin has changed into a Plus sign dot, this shows that the breakpoint is a conditional one.

Now press F5 to start the debugging the notice that the breakpoint will be hit only when the condition is met (here when i == 90).

Hope this helps in your debugging process. Happy debugging !!