views:

122

answers:

4

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?

+3  A: 

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)
Noon Silk
When I right click on the breakpoint I don't get an option called condition. All I get is an option to delete or disable the breakpoint.
Phenom
That is strange. What version of VS?
Noon Silk
I'm using Visual C# Express Edition version 9.0.30729.1 SP.
Phenom
+1  A: 

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.

Bob
I'm not sure what it is, but it's being shown in a textbox that holds integer values. The values in the textbox should never be negative.
Phenom
A: 

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.

Steve
What is the call track, and how do I view it?
Phenom
He means the 'call stack'.
Simeon Pilgrim
+1  A: 

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)

data_smith