Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add entry to list while debugging in Visual Studio

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.

like image 386
brainimus Avatar asked Jun 22 '10 14:06

brainimus


3 Answers

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.

like image 95
Matt Greer Avatar answered Oct 20 '22 06:10

Matt Greer


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 )

like image 29
digEmAll Avatar answered Oct 20 '22 06:10

digEmAll


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...

like image 32
JMarsch Avatar answered Oct 20 '22 07:10

JMarsch