1

I noticed that the parameter a evaluates to diff in the watch window (even if b is non-zero), when breaking on the return statement line, which doesn't make sense to me. If uncommenting the line above, that doesn't happen. Any ideas? Do you guys get the same result? I used Visual Studio Ultimate 2013 12.0.40629.00 Update 5, debug build.

public decimal Subtract(decimal a, decimal b)
{
    var diff = a - b;
    //var test = a;
    return diff;
}
Erresen
  • 1,923
  • 1
  • 22
  • 41
  • Mine is as expected: https://imgur.com/a/XQ49C – Erresen Jan 20 '18 at 16:50
  • @dasblinkenlight Sometimes you want to debug a release version (with debug info turned on), that's why I was specific about it, since this is probably a compiler issue –  Jan 20 '18 at 17:00

1 Answers1

1

since this is probably a compiler issue

Depends on your definition of "issue". What you see is not unexpected if you are debugging an optimized build. The C# compiler is unlikely to coalesce variable storage (I'm guessing it simply can't), but the JIT compiler, which is what creates the native code that actually executes, certainly can and most likely would.

So, your variable a, being unused after the assignment to diff, is having its storage location reused for the variable diff, rather than allocating a whole new location for it.

Since both variables are using the same location, when you watch the value in the debugger, changing one variable has the effect of changing the other.

For more discussion on debugging optimized builds, see:

Cannot obtain value because it has been optimized away
What is the point of nop in CIL

The second link doesn't really pertain to the "reused variable slot" aspect per se, but Hans' answer does include the sentence "You can still debug a Release build, it is however a pretty confounding experience that makes you doubt your sanity", which IMHO sums up the whole broad topic nicely. :)

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136