tags:

views:

171

answers:

3

When I programmed in C/C++, I often include pointer values in tracing. This helped correlate objects between trace messages. In C#, I don't have a pointer value available I can trace. Are there any good alternatives for traceable object IDs??

I don't know offhand how to get the underlying memory address, but even if I did that wouldn't help much as the GC could move objects around.

+2  A: 

Use Object.GetHashCode(). The GetHashCode() method can be accessed from all objects since every class in C# derives from Object. But its guaranteed to be unique only when Object.GetHashCode() is called and its result is used in some way for the generation of hash codes for user defined classes. Please note this is not an absolute guarantee you may still end up getting the same Hashcode for more than one object.

SDX2000
+2  A: 

Add a class variable that is incremented on each constructor call. Assign this class-variable as your own index to the class.

class foo
{
  private static int counter;
  private int instance_counter;

  public Foo()
  {
    instance_counter = counter;
    counter++;
  }

  public string toString()
  {
    return "Foo "+instance_counter.toString();
  }
}

may not compile out of the box, I have no compiler here.

+5  A: 

A tip: inside Visual Studio, you can right click on the object in the locals/watch window, and select "Make Object ID" to give the object a unique tag.

http://blogs.msdn.com/saraford/archive/2008/09/16/did-you-know-how-to-create-an-object-id-to-keep-track-of-your-objects-314.aspx

Brian