Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code when breakpoint is hit?

In the Immediate window, I can execute a line of code. I can also set a breakpoint at a particular point so that when the breakpoint is hit, the program stops and I can run my line of code in the Immediate window. Is there any way (extensions included) to do this automatically?

like image 513
Alex Avatar asked Apr 22 '13 16:04

Alex


2 Answers

More or less. You can rightclick any breakpoint and select "Actions..." (VS 2017, read on for older versions)

The only option in there is to print a message, which is usually sufficient, but you can run arbitrary code in there. For example: {Console.WriteLine("Hello World")}

Screenshot of Visual Studio 2017 Actions breakpoint

In older versions of Visual Studio, the option is available by rightclicking and choosing "When Hit...":

Screenshot of Visual Studio When-Hit breakpoint

This will output:

Hello World
Expression has been evaluated and has no value

This means you can call arbitrary methods. Any other side effects will carry to your running application. I sometimes use it to temporarily patch a problem with the code without restarting the 64-bit application.

Keep in mind that this is exceptionally slow compared to normal program execution however.

like image 90
Thorarin Avatar answered Oct 16 '22 02:10

Thorarin


The answer for Visual Studio 2017 is similar to Thorarin's answer, but some UI components have changed.

In visual studio 2017, the menu item you are looking for is "Actions".

Right click breakpoint, and select "Actions", and then place your code you wish to execute within brackets { .. code to execute .. } in the "Log a message to output window" field.

like image 43
James Wierzba Avatar answered Oct 16 '22 03:10

James Wierzba