A New Internet Library: Add Your Website/Blog or Suggest A Website/Blog to our Free Web Directory http://anil.myfunda.net.

Its very simple, free and SEO Friendly.
Submit Now....

Wednesday, March 26, 2008

Conditional debugging in Visual Studio .NET

Whenever you have a piece of code that runs more than once, it can create a problem for debugging. Suppose, for example, that you have a loop that works for 100 iterations, but then fails for some reason. (This could easily happen if you were processing elements in a large array, for example.) Setting an ordinary breakpoint wouldn't help much, since the breakpoint would be hit every single time through the loop.

Visual Studio lets you set breakpoints conditionally, however, so the program will only stop if a particular condition is met. To give a breakpoint a condition, set the breakpoint normally, then right-click and select "Breakpoint Properties."



Breakpoint Properties

You can make a breakpoint conditional in several ways:
  • You can tell the breakpoint to trigger only after it has been hit n times. This is the "Hit Count" method. Note that this is a count of how many times the breakpoint itself is encountered, so if the breakpoint is inside an 'if' statement, the "Hit Count" may or may not match the number of iterations of the loop.

    You can also tell the program to stop when the hit count is anything above n, or even if it's a multiple of n (so you can check on a loop's progress every 500 iterations, for example.

    Click the "Hit Count" button on the Breakpoint Properties window to change these settings.

    reakpoint: Hit Count

  • You can tell the breakpoint to stop the program only if some (arbitrary) condition is met. You might do this if there's a particular scenario you're interested in studying (for example, you might want to observe all situations in a loop where some variable is negative).

    From the Breakpoint Properties window, click the "Condition" button and set whatever condition you want:


    Se a Condition

  • If you're interested in stopping whenever some variable (or expression) has changed, you can set a conditional breakpoint in a different way. In the "Breakpoint Condition" window, there are two choices marked "is true" and "has changed." We used the first when we wanted to stop the program only under certain circumstances. The second can be used to monitor a variable.

    If you entered 'someVar' in the "Condition" field, and checked "hasChanged," then the breakpoint would only stop on iterations where the value of 'someVar' is different from when it was last seen. Although conditional breakpoints are most often useful inside loops, there's no reason they must be used inside a loop. This is just one more tool you have available; it may be handy in any number of situations.

Dotnet-Interviews