Tips & Tricks: How to tell VS to modify variables in the runtime for us?


Today, I'd like to share with you a simple but useful trick. Imagine yourself that you are debugging an application and you find a place with the following very simple code:
var flag = ReadConfiguration();
if (flag)
The problem is that the flag variable is set to false but you need to check what would happen if it is set to true. Of course you can easily change the value of this variable in Visual Studio. But what would you do if this kind of code is executed dozens, hundreds... of times and every time the flag variable must be set to true? One solution is to modify a configuration, another might be to change the source code. However, all these things require an additional action. It would be much more better to tell Visual Studio to do it for us. How? In order to achieve desired effect we can utilize breakpoints and custom actions. I'll show how to do it in Visual Studio 2015.

Firstly, put a breakpoint in the line with if.

Right click the breakpoint and from a context menu select Actions... Then in the text box enter {flag = true}. You can even use IntelliSense here. At the end click Close button.

An that's all. Now, if you run the application under debugger control a flag variable will be set to true whenever a line with a breakpoint is executed. What's more this trick also works with other types of variables and you can also execute methods in this way e.g.:

At the end I want to say 2 things. Custom actions are usually used to write diagnostic messages to Output window. This trick works because in order to write a message Visual Studio has to execute some code and this code can have side effects. Besides, you can also use this trick in older versions of Visual Studio. The only difference is that from a context menu you need to select When Hit... option.


Post a Comment