Wednesday, October 19, 2011

Preview of method return value in VS Debugger

I'm probably not going to invent a wheel here, but this is something I'm quite satisfied to figure out. One of the things that annoyed me when using Visual Studio Debugger was that I coudn't see the value that will be returned from a method I'm currently debugging, i.e.:

public int Test()
{
return GetSomeValue();
}

When in line 3, I would expect debugger to allow me to see the value returned by GetSomeValue() method as it certainly knows it. I used to modify the code so that I have a temporary variable for the value or repeat the method call in immediate window. Both ways are quite bizzare.

It turns out that VS already can show the value to me pretty easily using Quick Watch window. I just need to select the expression I want to check and press Ctrl+Alt+Q (or choose Quick Watch from context menu).

Note that it is not exactly the preview of the value, that was returned by GetValue(). It is actually evaluating the selected expression, so be careful when the method being debugged has side effects. See this example:

public class DebugViewTest
{
private int counter;

public int Test()
{
return GetValueWithSideEffect();
}

private int GetValueWithSideEffect()
{
counter++;
return counter;
}
}

When checking the value returned from the GetValueWithSideEffect() method, we'll encounter the different value than normal execution path encounters, as Quick Watch will execute the method's code and increment the counter. Anyway, this method will be sufficient for our debugging in most cases.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.