In my program there is a variable that sometimes gets the value of -1. I want to find out exactly where in the code this is happening. In Visual C#, is there a tool or method I can use so that when the variable becomes -1, the debugging process pauses, and I'm taken to the line of code where the variable is set to -1?
Yes! Conditional breakpoint. Click as if normally adding a breakpoint, then right click the red dot, and choose "condition". Put the statement in brackets.
23: x++;
[x] Condition: (x == 2)
What type of variable? If it is a property, add a conditional breakpoint in the setter. Once that line is hit, take a look at the call stack to see where it was set from.
I will suggest first turn this variable into a property with setter and getter. Then refactor your code to make sure all the places that directly write and read this variable are not changed to use the setter and getter of the property. Finally, you can set a conditional breakpoint in the setter of the property to halt the program when the property is set to -1. Then look at the call track to find out where does this happen.
As suggested, turn the var into property, put breakpoint on the setter and when u hit the breakpoint, theres a windows in VS to see the call stack (debug -> windows -> call stack)
call stack is stack of calls - from what methods or functions you got to the point where you are. (main -> connectToDatabase -> connectToPort -> sendTcpPacket, for example)