Run to Cursor For Easy Debugging in Visual Studio Code
This post is for Visual Studio Code. To learn how to do this in Visual Studio Code, go Here.
The Run to Cursor command allows you to select a line of code where you want execution of the program to pause. This is very similar to a breakpoint. This is easier to use when you want to step through your code function by function or you want to jump around among different classes and components. You can use breakpoints for this, but often I find that I only use each breakpoint once or twice, and then I forget to turn them off.
Forgetting to turn off a breakpoint slows down debugging, because when you have moved on to focusing your attention on another area of code, the original breakpoint continues to be hit, forcing you to either remove the breakpoint or keep pressing continue while your mind is otherwise occupied trying to solve the issue at hand.
Breakpoints can just be cumbersome, especially when you have a lot of them. Normally when you create a breakpoint you need to click on the line of code, and then also click the continue execution button to get to the breakpoint. This is where the “Run To Cursor” comes to the rescue. It is sort of like a breakpoint that only hits one time and automatically deletes itself.
Even Better, the “Run To Cursor” command accomplishes both of these steps with a single action, although unfortunately there is not a default key binding for the run to cursor in VS Code, so you do need to open the context menu to access it, thus making the task require 2 clicks.
How to Use The Command
1. Open your Solution in VS Code, and start the project using the “Run and Debug” Tool. You will need to have a launch.json created for the project, and at least one breakpoint set in the code at a line before the area of code you want to debug. This is required because the Run to Cursor command is only available in break mode.
An alternative I like to use to avoid needing a breakpoint is to set the “stopAtEntry” property to true in the debug configuration in my launch.json
When this is set, the program automatically enters break mode at the first line of the Main Method. Notice how we are in breakmode, yet no breakpoint is set on line 18 below.
2. Right click to open the context menu on the line you want to debug and select “Run to Cursor”. The code will run and enter break mode once again on the line. You can also access this command through the command pallet by pressing control + shift + P, and typing in run to cursor. Remember this command is only available when you are already in break mode.