Share via


Debugger Tips, Tricks and Tools #6

Create an Object ID to keep track of an object while debugging

In yesterday's tip I hinted at another new feature of the debugger specially designed for C# and J# programmers. This is the ability to create an Object ID for any particular object during your debugging session, no matter what your current context is. In other words, it's quite similar to being able to get the address of an object in C or C++ so that you can refer to that particular object at any time during debugging. 

For example, given the following short program:

using System;

using System.Collections.Generic;

using System.Text;

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            List<string> stringList = new List<string>();

            stringList.Add("Hello");

            stringList.Add("World");

            foreach (string str in stringList)

            {

                Console.WriteLine(ReverseString(str));

            }

        }

        static string ReverseString(string str)

        {

            if (str.Length > 1)

            {

                return ReverseString(str.Substring(1)) + str.Substring(0, 1);

            }

            return str;

        }

    }

}

 

Put a breakpoint on the first line of ReverseString and run the program under the debugger. When the breakpoint is hit, hover your mouse over the 'str' variable, and on the DataTip that appears right click to bring up the context menu.

 

You will see the following:

MakeObjectId

Note the highlighted menu item called "Make Object ID". Select that and your DataTip will change to show the value of 'str' to be "Hello" {1#}". What's that "1#" doing on the end of the value? That's the Object ID. You can use that expression to refer to that particular instance of the object anywhere you can evaluate expressions in the debugger. 

To prove it, first press F5 again. You will break into ReverseString again, but this time the value of 'str' is "ello". Now add "1#" to the watch window. You'll see:

WatchObjectId

When you're done with that object you can right click on it in the watch window and choose "Delete Object ID".

Comments