Watching a variable in Visual C#? - c#

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.

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)

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.

Related

How to use Environment.StackTrace in a conditional expression for a breakpoint in VS2015

I'm trying to debug an issue and it would really help if I could have a breakpoint in the getter of a property, but I don't need to break every time it is called from a CanExecute call for some button in my UI. My thought was that I could simply condition the breakpoint on the call stack not containing that string, but that seems to not work. The best way I can think of to explain this is with an image of the settings and the output from the breakpoint being hit.
As you can see in the image, the Conditional settings for the breakpoint is outputted directly when it is hit, and in the output you can see it being hit a few times .get(): true - correctly. However, when it took this screenshot it was being hit with the condition being false, as seen in the output. The program halted as the breakpoint was hit, incorrectly.
Am I doing something wrong - is this possible at all? Seems to me like a bug in VS2015, the output can evaluate the bool correctly, why can't the breakpoint condition do that?
Edit, to annotate the image in case it gets lost sometime.
I have a breakpoint in the get method of a property that simply returns the underlying field. The Breakpoint settings show that there is a Condition on the breakpoint that defines it such that it should only be hit when the expression !Environment.StackTrace.Contains("CanExecute") returns true, i.e. only break when the Stack Trace does not contain the "CanExecute" string.
The Action part of the breakpoint settings simply outputs the function name and the conditional expression using $FUNCTION: {!Environment.StackTrace.Contains("CanExecute")}. The action is set to not continue the execution.
I don't know exactly why the stack trace information is not available inside breakpoint conditions, but there's a crazy workaround/hack you can do as an extension to a technique outlined in another answer
It won't work as "cleanly" if you use auto properties as it requires two breakpoints, and auto properties only have a single point to bind a breakpoint to but I'd imagine this isn't as useful for an auto property anyway.
Place the first breakpoint on the opening curly brace of the get method (set your cursor on the curly brace and hit F9). Set an action on this breakpoint; set "Log a message to Output Window:" to
{System.AppDomain.CurrentDomain.SetData("break", !Environment.StackTrace.Contains("CanExecute"))}
and ensure Continue execution is checked.
Place the second breakpoint on the return statement (set your cursor on the curly brace and hit F9). Set the condition on this breakpoint:
(bool)System.AppDomain.CurrentDomain.GetData("break")
Depending on your formatting, this may require the aid of the "Breakpoints" window Debug > Windows > Breakpoints (Ctrl+Alt+B) in case the curly brace and the return statement are on the same line. You can edit the action/condition by right clicking on the breakpoint in the "Breakpoints" window and selecting Settings
The cast to bool is required as GetData() returns an object and the conditional breakpoint won't do the cast for you.
It isn't pretty, and it doesn't work very well in a multi-threaded environment due to the global state, but it can be useful in a pinch. If you need multiple "conditional breakpoints" in this manner, make sure to use a different key in SetData()/GetData().
However, if you can, it's usually (depending on your compile time and access to the code vs debug symbols) quicker/easier to just temporarily edit the code to put the condition you want to break on.
e.g.
public Foo Selected
{
get
{
if (!Environment.StackTrace.Contains("CanExecute"))
System.Diagnostics.Debugger.Break();
return _selected;
}
}
*In the case of auto properties, you can use a pair of action breakpoints in the CanExecute() method before the property access to set "break" to true, and then after to set "break" to false, and for the condition use
(bool?)System.AppDomain.CurrentDomain.GetData("break") != false
to ensure it still breaks before and after CanExecute() but not during.

Tracking the state of the C# object using visual studio

I am working on a big project, with many dependencies, and somewhere in the code, something is changing the properties of the object I am tracking.
Is there any way of putting a breakpoint on variable, so that the program will stop when the object changes it's state?
I would recommend changing it to a property for public use, that way you can set a breakpoint on the get/set operations.
private int theVariable;
public int TheVariable
{
get
{
return theVariable;
}
set
{
theVariable = value;
}
}
Its also possible to set a breakpoint on when a variable changes value, yes, but I would recommend a property.
From MSDN:
Setting a Breakpoint When a Variable Changes Value To set a breakpoint
when a variable changes value From the Edit menu, click Breakpoints.
Click the Data tab of the Breakpoints dialog box.
In the Expression text box, type the name of the variable.
Click OK to set the breakpoint.
You can use Conditional Breakpoints
MSDN says:
A breakpoint condition is an expression that the debugger evaluates
when a breakpoint is reached. If the condition is satisfied, the
debugger looks at the How to: Specify a Hit Count to determine whether
to break (or execute another specified action).
This allows you to put expressions when you can tell Visual Studio to break.

Bug tracking by debugging when a variable changes

I'm a beginner at programming and having a very difficult time tracking down bugs, this happens because usually place a variable on watch, and keep pressing f5 until i notice some change. I'm on visual c# 2010 and i have 18000 lines of code, so only with some luck i do get to catch the problem.
Is there a way to instantly go to the line of code when a variable changes?
You can change your variable into a property and put a breakpoint on the setter. Then you can have a single breakpoint that will hit each time a piece of code changes its value.
So if you have:
int myVariable;
Change it to:
int myVariable {
get;
set; // <-- Put your breakpoint here
}
This sounds like a design problem. Ideally, you should limit the places where a variable changes to very specific locations in your code. This is one reason to avoid global variables and static variables unless you have very good reasons to use them. Even then, you should define accessor methods as an interface for these variables rather than changing them directly.
As you debug your code, I suggest you look for ways you can improve it so that debugging isn't so difficult in the future.
You can have conditional breakpoints, that will only be hit when a condition is met.
So, assuming you have an index variable indx, you can put a conditinal break point, saying only stop when value = 7, and then it'll stop there when you're condition changes...
Have a look at this msdn page
and at this youtube tutorial.
In native code, your best bet would be to setup a data breakpoint. A data breakpoint fires when the data changes, irrespective of where the change comes from.
You can't do this for .NET however. You can't ask the debugger to break when the value of a variable changes. But, not all hope is lost. Do a "Find Usages" or "Find References" on the variable in question to find all places in your code that make use of the variable. Then set a breakpoint at each of those locations to see when the value of the variable changes.

How to set a breakpoint in every method in VS2010

I have a bigger (c#) WPF application with n-classes and m-methods. I would like to place in every single method a breakpoint, so everytime i press a button in my application or any method gets called, i would like the application in VS2010 to hit that breakpoint. I want to understand the flow/progress of the application.
And since i have many methods i would rather not place manually in every and each of them a breakpoint.
Is there any command or tool to place everywhere in my VS2010 solution a breakpoint?
edit: maybe something like the following addin: http://weblogs.asp.net/uruit/archive/2011/08/04/visual-studio-2010-addin-setting-a-class-breakpoint.aspx
edit2: there are some answers but none of them seems like the straight forward easy solution. Anything else?
EDIT: tested only with C++
I came across this article that shows how to set a breakpoint at the beginning of every method in a class. I've tested it with VS 2010. The basic process (when using Visual C++) is:
Go to Debug > New Breakpoint > Breakpoint at Function (Ctrl + B).
In the Function field, insert MyClass::*
This will show up as a single breakpoint in the Breakpoints window, but as soon as one of MyClass's methods is hit, you'll see a breakpoint at the beginning of every function in MyClass, and all of these will be "children" of the original breakpoint in the Breakpoints window.
I imagine this works with C# as well.
This answer suggests a macro that will do as you ask, but my personal recommendation would be to use a profiler instead - one that lets you pause and resume profiling on the fly (nearly all of the commercial profilers do), and then hit the "Start Profiling" button just before you do your button click. Viewing the call tree in the profiler is often a very convenient way of gaining insight into what an application is doing, much more than stepping through in the debugger.
UPDATE: This feature exists in a Visual Studio extension that I'm working on called OzCode. With OzCode, when you click on the icon next to the class definition, you'll see the QuickAction:
Here's a quick and dirty way to do it using a simple text replace:
Format your C# file so that all of the indentations are lined up. You can do this in Edit > Advanced > Format Document
Open up text replace with Ctrl+H
Set the "Text to Find" field this "^ {".
Set the "Replace" field to this " {System.Diagnostics.Debugger.Break();"
Click the little "Use Regular Expressions" button in the window
Click "Replace All" or hit Alt+A
If your file has any classes with nested enums, classes, or structs, you'll have some compiler errors. Remove the Debug calls from them until your code compiles. If your nested classes have their own methods, you'll have to run this process again with more tabs in the replace strings.
How this works: This uses the Visual Studio document formatter and assumes that all methods in a file start with two tabs and then a "{". So any line that starts with two tabs and a "{" will get replaced with the same two tabs, the same "{", and a call to the Debugger.
If your file has nested enums etc., you'll get compiler errors because the text replace doesn't discriminate between methods and enums. For example, you'll see this:
enum MyColors
{ System.Diagnostics.Debugger.Break(); //error here
Red,
Green,
Blue,
}
If you want the ability to disable these breakpoints, the best way I can think of is a simple bool. Somewhere in your code, insert this:
#if DEBUG
private static bool _ignoreDebug = false;
#endif
(I put the #if DEBUG in there as a flag that this code is only for debugging. It's not necessary) Then in step #4 above, use this replace string instead:
" {if(!_ignoreDebug){System.Diagnostics.Debugger.Break();}"
Then when you hit a breakpoint and don't want to hit any more, in the watch window type this and hit enter _ignoreDebug = true. To turn it back on you'll need to insert a manual breakpoint somewhere that has access to the _ignoreDebug bool.
To remove all of this from your code, either do another text replace, or just edit undo everything.
I think you create an 'aspect' for it using a tool like: postsharp
Aspect oriented programming allows you to add code to the start or end of every method (through a postprocessing step). So it's trivial to add the line:
System.Diagnostics.Debugger.Break()
to every method (without actually editing all your sourcecode).
More typically it is used to add log statements to the beginning of every method like: "Entering method DrawLine(x=30,y=80,z=12)" and at the end of a method: "Leaving method DrawLine(x,y,z)". Which makes following the flow of your program easy
You can use my Runtime Flow extension to see all methods called after press of a button without setting breakpoints.
You can use System.Diagnostics.Debugger.Break() on entry to your method.
Something like this perhaps with a bool that you set at the scope?
#if DEBUG
if (BreakPointEveryMethod)
System.Diagnostics.Debugger.Break();
#endif
There will be a quick way too add this for sure in notepad++ but I am not sure there is a quick and easy way for you to achieve this through a simple command line.

When is my C# property initialized?

I'm a little confused about when exactly my Property is being initialized.
Suppose I have a property declared like this:
private Dictionary<string, Dictionary<string,string>> MessageLookup
{
get
{
return messages ?? doSomething();
}
}
The doSomething method populates the messages Dictionary and returns it.
My question is, when is this code run?
If I place a breakpoint into the doSomething code, it isn't hit, but the MessageLookup property is holding data (this is the only place it is initialized) when I view it in the debugger.
Is this code run at construction? does the debugger run it automatically when I hover over the variable name? If so, why isn't the breakpoint hit?
That code is run whenever anyone refers to the property, and not before.
If you use the debugger, you'll see it because the debugger tries to fetch property values automatically (so you can see the state of the object). I don't know whether the debugger ignores breakpoints while it's evaluating properties for itself - that would explain everything.
Try running your code not in a debugger, and make some code access your property:
var lookup = someObject.MessageLookup;
Make doSomething() dump a stack trace and you'll see what's going on.
It is run when your property is first evaluated. No background stuff going on.
I'm guessing you're not seeing this because you use Quickwatch to inspect your object. At that point it will get executed and your breakpoint will be skipped.
Property getters (and ToString() for that matter) are assumed to be pure, which basically means evaluating it has no side effects. You should rewrite the code to adhere to that assumption or you'll face nasty consequences. If must use lazy initialization at access time, use a GetMessageLookup() method instead.

Categories