While debugging the applications in visual studio, in may instances it many require to call a specific method when a breakpoint is hit. It may be because of just to verify some output or check some variables values. We can perform that part either using immediate window or execute those method in some other debugging session. However, all of them are a bit time consume! and while debugging we as a developer need to be very productive. So, here is one quick tip by which you can achieve the same in a smart way – just by using breakpoint itself. Yes ! you can invoke a method automatically when breakpoint is hit using some advanced breakpoint options.
In this case, you need to use the “When Hit” option from the break point context menu.
Fig : Select “When Hit” option from breakpoint context menu
This will bring the following “When Breakpoint Is Hit” dialog control
Fig : When Breakpoint Is Hit – Dialog Control
The main purpose of this screen is something different than what we are trying do achieve now! This screen is used for – print a message that can display the method name, process name, thread name etc when the breakpoint hit with “Print a message” check-box is checked.
To call a method, you need to provide the method name by placing it in curly braces, with in the message text box. As shown in the following image, a breakpoint is set on the line no 14, and it is calling Method1(), when the breakpoint is getting hit.
Fig : When Breakpoint Is Hit – Calling a Method
If you run the application, when the debugger reaches to the breakpoint, you will found the following output, where we can see the output of “Method1()”, whereas we haven’t called the method anywhere from the application.
Fig : When Breakpoint Is Hit – Calling a Method Output
So, you can call a method automatically irrespective of the method execution sequence with the breakpoint hit. You can also print some code variable, values using the same approach. And, the best part is, it is already written with in the dialog window – that how we can use it with code variables !
Hope this will help you!