10 November 2011

Debugging immediate variables

Here's a neat Visual Studio debugging trick I just stumbled on today by accident. Sometimes, it can be very handy to be able to refer back to information from another frame in the stack, or from a previous call to the same function.



Step 1

When you're at a location of interest, use the intermediate window to declare a new variable and assign a value to it. (Remember to give it a type declaration or 'var').


// Type this into the 'Immediate' window
var tmp = data;



Step 2

Now, when you're at a completely different location, either in a different method, or even at a different calling of the same method, you can still inspect your immediate variable in the watch window.




Obviously the temp variable is not going to automatically update if the source it came from gets updated, but it can still be pretty handy sometime, for example to compare two values to see if they're the same.


Presumably we're also holding onto a reference now that would prevent it from being garbage collected, so in a large environment it might be a good idea to set the temp variable back to null when you're done with it.


What happens if you set it to a variable name that is then used at a subsequent break point? Answer: it gets blown away and replaced with the new value (and type).

No comments: