TL;DR – In Visual Studio, you can ‘pin’ an object instance and inspect its state at any point during the lifetime of your application and even using the pinned object as a breakpoint condition.
It has been a long time now that i really wanted to make a series on the Visual Studio advanced debugging tips and tricks. In this series i won’t cover anything that seems trivial for my taste, rather i will talk about some of the less ‘popular’ features of the Visual Studio debugger.
As it turns out, a lot of developers out there are not aware of the many amazing features Visual Studio brings into their professional toolboxes. One of them is ‘Object Pinning’.
Lets start with some use cases and common solutions.
- When you hit a breakpoint in a function and you want to inspect this function’s variables, you can look at the ‘locals’ window in VS.
- When you hit a breakpoint in a function that is X stack frames deep, and you want to inspect one of the calling function’s variables, you will use the call stack window.
- So far the problems and their solutions have been trivial. How about inspecting an object instance that is not in your function’s scope, and not in you call stack scope either?
Well, there is a pretty simple solution, and its called ‘Object Pinning’. When you hit a breakpoint, you can add an object to a ‘watch’ window by right clicking the variable and choose ‘Add Watch‘ from the context menu.
Once the variable is in the ‘Watch’ window, you can right click it and choose ‘Make Object Id‘ from the context menu.
At this point VisualStudio will assign a number to this instance, and you will be able to inspect the object at any point in your application by typing the dollar sign ($) and the number of the instance next to it (if this is the first time during the lifetime of your application that you are pinning an object, then your object should get an id of $1).
Here is the interesting part, you can actually use this pinned object as a condition for a breakpoint! This is amazing really, i encourage you to try this out on your own.
Have fun coding,