7

Is it possible to break execution when a watch variable (not a property, just a normal variable) changes to see where the change occurred? I searched and found this question which relates to properties it seems which is not what I'm looking for.

This variable is used several times in several thousand lines of code, but it is only changed from null when a problem happens. We are trying to track that problem down.

Community
  • 1
  • 1
ldam
  • 4,412
  • 6
  • 45
  • 76
  • 1
    Possible duplicate of this question: http://stackoverflow.com/questions/7488155/can-i-set-a-breakpoint-when-variable-is-getting-specific-value-in-net – Matthew Watson Feb 14 '13 at 11:39

2 Answers2

6
  1. Create a breakpoint (f9) around the variable
  2. Right-click on the red circle of the breakpoint and click on "Condition..."
  3. Type in the name of the variable, and change the radio to "Has changed"
  4. The breakpoint should now have a + in it to indicate that it is conditional

However: frankly, I find the following simpler and much more efficient - especially for fields; say we start with:

string name;

we change it just for now to:

private string __name;
string name {
    get { return __name; }
    set { __name = value; }
}

and just put a break-point on the set line. It should still compile, and you can see the change trivially. For more complex cases:

private string __name;
string name {
    get { return __name; }
    set {
        if(__name != value) {
            __name = value; // a non-trivial change
        }
    }
}

and put the breakpoint on the inner-most line; this bypasses code that sets the field without actually changing the value.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • conditional break points break on the line that you placed them...I don't see how this would cause it to break where the variable actually got changed. the set method works, but tried the former and it doesn't. – Christopher Pisz Jul 27 '17 at 14:34
  • Excellent solution! Implementing this method in conjunction with Call Stack works nicely. – MQuiggGeorgia Jan 05 '18 at 16:56
  • 1
    This was one nice thing about Visual Basic 6. You could set it to break when a variable changed, regardless of what line it was at. – Eric Dec 04 '18 at 19:49
0

inside vs code:

  1. right click on breakpoint, choose EditBreakpoint right click, edit breakpoint

  2. in the Expression, enter an expression as condition, when to stop the program e.g. SomeVariable == 0x7f2c44a31f98 (0x7f2c44a31f98 is the address of the variable to be watched) enter an expression for break condition

  3. press enter

For our example, when SomeVariable is equal to 0x87654321, it won't stop, once the SomeVariable is equal to 0x7f2c44a31f98, it will stop

Chenzhuo
  • 1
  • 1