Inspect out of scope Objects

As a C++ programmer I always enjoyed the luxury of accessing objects by using their addresses in memory. However things are quite different when you want to access any object by their memory address in the .NET/C# world. Primary reason is of course that in managed application GC can move around objects and therefore the addresses can change. Recently I learned a new trick where you can keep track of objects even though they may be out of scope (as long as they are not garbadge collected). Its called “Make Object ID”.

Let’s say we have simple code as follows. Not the most useful class but its enough to serve the purpose of explaining the idea.

namespace Demos
{    
  class Customer    
  {        
     public int Id { get; set; }        
     public string Name { get; set; }    
  }
  class Program    
  {        
    static void Main(string[] args)        
    {            
      Method1();            
      Console.ReadKey();        
    }
    static void Method1()        
    {            
      Method2();        
    }
    static void Method2()        
    {            
      Customer Cust = new Customer() { Id = 1, Name = "Foo" };        
    }    
  }
}

Set a break-point in Method2() where we are instantiating Customer object.  Once you hit the breakpoint and Customer object is instantiated, you can either hover the mouse over the data tip for Cust object. At this point, if you right click on the data tip, you get this option of “Make Object ID” in the context menu as shown in the figure below.

You can do same thing either through Local or Auto debugging windows as well.

What “Make Object ID” option does is that it assigns it an integer value that could be used globaly to uniquely identifier this objects. When accessing this identifer, you have to append a # with that integer. So in the example code above, step out of Method2(). Now even if you are out of scope for this Customer instance, let’s go in immediate windows and type 1#. As in figure below, you can still inspect this object.

You can always clear this object by choosing “Delete Object ID” option when inspecting it in the Watch window. If you want to get more insight into how this feature is implemented, I encourage you to read this blog entry.

Until next, happy Debugging.

Advertisements
This entry was posted in .NET, Debugging. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s