Everything about my daily life as a programmer/Electrical Engineer!

Keep an eye on a reference.

When debugging I often find myself wishing I could just watch a single object throughout its life cycle. This is especially useful for debugging state problems (I’m thinking detached row error). Someone is modifying the state of your object and you need to figure out who. The problem lies in scoping. Every time you step in you have to change the watch window statement to track your objects state.

What you end up with is a nasty watch window.

The immediate window comes to the rescue!  Simply declare a variable with a globally unique name (DataRow watchMyRow=_dr;) for example. Then go to the watch window and add a watch for watchMyRow.  watchMyRow is always in scope. So now step through at your leisure and find the offending entry point and step deeper. Its that easy!

 

So we will start with a simple test program that calls methods with several different names and types.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MyObject val = new MyObject();
Method1(val);
Method2(val);
Method3(val);
}

static void Method1(MyObject obj)
{
obj.state = 1;
}

static void Method2(MyObject myobj)
{
myobj.state = 2;
}

static void Method3(object obj)
{
((MyObject)obj).state = 3;
}
}

public class MyObject
{
public int state = 5;
}
}


We set our break points.



image



And at the end of the cycle our watch window looks like this! 



image 



All to track the same value on the same object!



 



The real problem is that with events thrown into the mix it becomes impossible to track state on some foreign object (Detached Row I loathe you!).



Now lets do the same example with the immediate window.



Our first break point gets hit. We type MyObject WATCHMYOBJECT=obj; into the immediate window.



image



Next I add that variable to the watch window.



image



Finnally after the many function calls this is the result.



image



 



I only had to watch one object the entire time! Now if I can only build a VSADDIN to automate this process (evil grin)!

No comments: