Setting conditional breakpoints

Conditional breakpoints are another hidden gem when it comes to debugging. These allow you to specify one or several conditions. When one of these conditions are met, the code will stop at the breakpoint. Using conditional breakpoints is really easy.

Getting ready

There is nothing you specifically need to prepare to use this recipe.

How to do it…

  1. Add the following code to your Program.cs file. We are simply creating a list of integers and looping through that list:
    List<int> myList = new List<int>() { 1, 4, 6, 9, 11 };
    foreach(int num in myList)
    {
        Console.WriteLine(num);
    }
    Console.ReadLine();
  2. Next, place a breakpoint on the Console.WriteLine(num) line of code inside the loop:
    How to do it…
  3. Right-click on the breakpoint and select Conditions… from the context menu:
    How to do it…
  4. You will now see that Visual Studio opens a Breakpoint Settings window. Here we specify that the breakpoint needs to be hit only when the value of num is 9. You can add several conditions and specify different conditions. The condition logic is really flexible:
    How to do it…
  5. Debug your console application. You will see that when the breakpoint is hit, the value of num is 9:
    How to do it…

How it works…

The condition is evaluated on every loop. When the condition is true, the breakpoint will be hit. In the example illustrated in this recipe, the true benefit of a conditional breakpoint is somewhat lost because it is a very small list. Consider this though. You are binding a data grid. Items on the grid are given specific icons based on the status of the item. Your grid contains hundreds of items, because this is a hierarchical grid. You identify the primary ID of the item which is bound to the grid. This primary ID is then passed to other code logic to determine the status, which determines the icon displayed.

To debug and press the F10 key through hundreds of loops is not productive in any event. With conditional breakpoints, you can specify a value for the primary ID, and only break when the loop hits that value. You can then go straight to the item that is being displayed incorrectly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.59