DEV Community

Felipe Marques
Felipe Marques

Posted on

5

Visual Studio breakpoint with conditions

🇧🇷 Versão em português

This is a simple and quick tip, maybe you already know it, but I don't, even after 10 years working daily with visual studio and C#, so I decided write about it.

If you've ever had to debug code that takes several attempts to evaluate behavior on just a certain condition, you already needed something like a breakpoint with conditions. And as its name says, VS provides this feature for us.

To exemplify, I made a simple code that prints 10 random numbers on a console.

Console.WriteLine("Begin");
var rnd = new Random();

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine($"{i}: {rnd.Next(10)}");
}

Console.WriteLine("End");
Console.ReadLine();
Enter fullscreen mode Exit fullscreen mode

If you put a breakpoint, as in the image below, the debug will stop at it all 10 executions of the loop.

Image description

However, you can must observe the loop behavior just when the condition is i==5, in this case, right click on the breakpoint and put your condition.

Image description

The conditions are specified as in the language and you can use any variable available in that scope, in this case I'm using the i variable.

Image description

Image description

Here is a simple example video of the whole process.

I hope you like and if you don't know this feature, comment there.

Image of Bright Data

Maximize Data Efficiency – Store and process vast amounts efficiently.

Optimize your infrastructure with our solutions designed for high-volume data processing and storage.

Optimize Now

Top comments (3)

Collapse
 
pbouillon profile image
Pierre Bouillon •

This is indeed a very useful feature, especially when you need to debug a specific case in a when iterating on a huge collection!

As a side note, the feature is also available on VS Code and works in the same way

Collapse
 
felipemsfg profile image
Felipe Marques •

I didn't know that is also available in VS Code, thanks for the tip.

Collapse
 
utpaldas20 profile image
utpaldas20 •

Informative

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay