views:

43

answers:

3

I have a point in my code where I have added a breakpoint. What I would like to do when the debugger stops at the break point is to modify the contents of a list (specifically in this case I want to add entries). How do I modify the contents of a list while debugging?

Edit: The list is a list of strings.

+6  A: 

Use the immediate window (default of CTRL+D,I with C# keybindings, or it's in the Debug > Windows menu).

From there just invoke myList.Add(foo), it will come back saying the expression has been evaluated and has no value, but the side effect of adding foo occurs.

Matt Greer
+1  A: 

Also in the watch window you can perform single-line statements (or better expression).

Just write something like:

myList.Add("myNewValue")

and press ENTER It should works (at least has always worked for me )

digEmAll
Yeah that works too. Both approaches have the limitations of not supporting lambda expressions. I really hope VS2010 SP1 fixes that.
Matt Greer
Unfortunately, VS2010 doesn't fix that (I've tried it), along with the edit-and-continue issue on methods using lamba expressions. I supposed they're very related (if not the same) and not so easy to implement
digEmAll
+2  A: 

There is a technique that you can use to inject code from within a breakpoint. It's easy, and it works.

  1. Set a breakpoint
  2. Right-click on the breakpoint, and choose "conditions"
  3. Put your line of code in the condition (it does not have to return a bool)
  4. Run

When your breakpoint is hit, the code will execute, and the debugger will NOT stop on the breakpoint (because you didn't return a bool).

I got this tip from the Visual Studio tips blog: http://blogs.msdn.com/b/zainnab/archive/2010/05/04/set-a-complex-breakpoint-condition-vstipdebug0022.aspx

Here's an example program that illustrates the technique:


        static void Main(string[] args)
        {
            List l = new List();
            Console.WriteLine(l[0]);
            System.Console.ReadLine();
        }

If you run this code as-is, you will get an exception. However, before yourun it, add a breakpoint to hte Console.WriteLine() line.

Right-click on the breakpoint, and choose "conditions" In the condition dialog, add the following code:

l.Add("hello")

Now run.

Clearly, a person could get into a lot of trouble with this "feature" -- you can change the behavior of your application with breakpoints such that an independent build of the code behaves differently from when it is run on your machine in your debugger. So, be very careful...

JMarsch