Visual Studio Debugging Tip – Change A Value Automatically With A Silent Breakpoint

Your debugging your code, and you have the need to change the value of a variable automatically without changing any code. Perhaps the URL of a production webservice is valid and cannot be changed in code, but you want to switch it to a development URL There are several ways of doing this, but only when the code execution has stopped at a breakpoint, and you need to change it every time manually.

Here is a good trick to set a ‘silent’ breakpoint (one that will never break the code), which will always change the value you want to change, for as long as the breakpoint is enabled.

Here’s an example:

class Program
{
    static void Main(string[] args)
    {
        var productionUrl = "http://www.mydata.com/productionservice.svc";
        Console.WriteLine(productionUrl);
        Console.Read();
    }
}

In this simple example above, we have a local variable holding the value of a production webservice URL, and we simply write it to the console

breakpoint1

Just as you expected.

Now add a silent breakpoint like this, before the variable is used

breakpoint2

as you can see, we’ve high-jacked the conditional breakpoint feature. This breakpoint will never stop code execution, BUT it will always change the value of a local variable, without changing any code.

breakpoint3

Now, when we run our code we get this output

breakpoint4

Which is a great way of changing state without changing any code. You can group and name breakpoints, and manage them in the breakpoints window – so they can be switched on and off in different scenarios.

A word of caution though, leave one of these breakpoints on accidentally, and you could have a head-scratcher on your hands that will take hours to work out.

The following two tabs change content below.

Dean Chalk

WPF & WinRT/XAML developer contracting in the UK investment banking industry.

3 comments

  1. A well designed application will read stuff like this from a properties file. All you should need do is restart the server with the changed properties.

    1. Examples demonstrating the use of a principle often don’t make sense in the real world. It’s not literally something you would do but it can be shown in just a few simple lines by disconnecting from that for just a couple seconds.

  2. Thanks for this information.
    I knew the conditional breakpoint feature allready, but haven’t tried to assign values with it, which I’m sure comes in handy.

    But please be also aware, conditional breakpoints have a huge performance impact.

Comments are closed.