Visual Studio Debugging - How To Set a Breakpoint Condition

Do you iterate through long for loops or while loops? Tired of pressing F8 or F5 just until you meet a certain condition while debugging in Visual Studio? I didn't  know that this was possible (haven't tried in Eclipse) until a colleague told me How To Set a Breakpoint Condition in Visual Studio.

How To Set a Breakpoint Condition in Visual Studio

Let's assume that you have the following set of code... The code below does nothing but to print names from an array of string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Text;

namespace BreakpointIfTest
{
    class Program
    {
        private static string[] names = { "Tim", "Gerald", "Keith", "Cruizer", "Rolvin", "Jared", "Chris", "Jops", "Devpinoy" };

        static void Main(string[] args)
        {
            foreach (string s in names)
            {
                Console.WriteLine(s);
            }
        }
    }
}

 

Suppose we set a break point at the line... Console.WriteLine(s);

 

Visual Studio Debugging - Set a Breakpoint

 

and we want the breakpoint only to HIT when the value of  the variable "s" is "Keith". What you do is right click on the breakpoint (the red circle) and choose "condition".

 

Visual Studio Debugging - Make a Breakpoint Condition

 

A window will pop up prompting for a breakpoint condition, enter s == "Keith"

 

Visual Studio Debugging - Set a Breakpoint Condition

 

Now run and debug your application and you will see that the breakpoint will only hit if the value of "s" is Keith". ;)

 

Visual Studio Debugging - Run and Debug

 

Tell me if it helps you. I hope this saves you some time debugging!

Published 05-31-2010 1:20 AM by lamia
Filed under: ,

Comments

Wednesday, June 02, 2010 8:45 PM by cvega

# re: Visual Studio Debugging - How To Set a Breakpoint Condition

If you don't like Visual Studio to "break" on every break-points., TracePoint is a good alternative.

TracePoint is a break-point with "continue execution" flag set.

For more information about TracePoint, see Scott's blog about it:

geekswithblogs.net/.../visual-studio-2008-debugging-tricks-ndash-tracepoints.aspx

Wednesday, June 02, 2010 8:47 PM by cvega

# re: Visual Studio Debugging - How To Set a Breakpoint Condition

Oh and if you have Visual Studio 2010., check out the collaborative debugging feature, where you can share your "breakpoints" to other developers in your team. It's very cool.

Wednesday, June 02, 2010 11:59 PM by lamia

# re: Visual Studio Debugging - How To Set a Breakpoint Condition

Whoah! Nice tips! Thanks master Chris!