1

I'm attempting to output the values returned by a method using a breakpoint action. The method contains multiple non-identical return statements, similar to this example:

double Foo(int bar, int baz)
{
    if (bar < 0)
        return Math.Sqrt((double)(baz - bar) * (baz - bar));

    if (bar % baz == 0)
    {
        if (baz == 3)
        {
            return bar / 2 * baz;
        }
        else
        {
            return Math.Pow(bar, baz);
        }
    }

    return Math.Log(baz, bar);
}

I'm looking for a way to output the return value without resorting to refactoring the method such that it stores the value in a variable, or putting a breakpoint on each return statement and having to write an individual action for each one.

The accepted answer of this question shows that it's possible to inspect the return value using the $ReturnValue keyword in the Immediate Window just before leaving the method.

The below image illustrates what I'd like to accomplish.

enter image description here

This won't work of course, and print:

DEBUG Result of Foo("1", false) = error CS0103: The name "$ReturnValue" does not exist in the current context.

While there are several keywords available, like $CALLER or $TNAME, I haven't found anything that will yield the return value.

Is it possible to print a return value in a single breakpoint action?

waldrumpus
  • 2,540
  • 18
  • 44
  • @SeM Output them in the Output Window – waldrumpus Mar 06 '19 at 13:02
  • Why just not to use `Debug.Print(yourMethodReturnValue)` on calling part? – SᴇM Mar 06 '19 at 13:04
  • There's only a limited list of key word (as $FUNCTION) you can return with breakpoint, and $ReturnValue isn't one, your error message comes from here. For output the return value of your function, I would use a simple Console.WriteLine() before returning the value. – Zoma Mar 06 '19 at 13:25

1 Answers1

3

You can put breakpoint after your method call and add breakpoint action like so:

static int Sum(int a, int b) => a + b;

static void Main(string[] args)
{
    int sum = Sum(1,2);
    {} // add breakpoint here
}

and action code:

Sum returned {x}.

it will print in output window:

Sum returned 3.

OR

Put breakpoint to your method's return part (in this case a + b) and add action like

$FUNCTION result is {a + b}

the output will be:

MyApp.Program.Sum(int, int) result is 3

SᴇM
  • 7,024
  • 3
  • 24
  • 41
  • The method is being called from several places all over the project; I would prefer to have a way to handle all calls without adding code to each call site. – waldrumpus Mar 06 '19 at 13:20
  • 1
    @waldrumpus I've added another method too. – SᴇM Mar 06 '19 at 13:24
  • Thanks for your update; the second method will require me to write an individual action for each return statement. Can this be avoided? See my update for an example. – waldrumpus Mar 06 '19 at 14:47