title: .NET unique object identifier
body: <p>Is there a way of getting a unique identifier of an instance?</p>
  
  <p><code>GetHashCode()</code> is the same for the two references pointing to the same instance. However, two different instances can (quite easily) get the same hash code:</p>
  
  <pre><code>Hashtable hashCodesSeen = new Hashtable();
  LinkedList&lt;object&gt; l = new LinkedList&lt;object&gt;();
  int n = 0;
  while (true)
  {
      object o = new object();
      // Remember objects so that they don't get collected.
      // This does not make any difference though :(
      l.AddFirst(o);
      int hashCode = o.GetHashCode();
      n++;
      if (hashCodesSeen.ContainsKey(hashCode))
      {
          // Same hashCode seen twice for DIFFERENT objects (n is as low as 5322).
          Console.WriteLine("Hashcode seen twice: " + n + " (" + hashCode + ")");
          break;
      }
      hashCodesSeen.Add(hashCode, null);
  }
  </code></pre>
  
  <p>I'm writing a debugging addin, and I need to get some kind of ID for a reference which is unique during the run of the program.</p>
  
  <p>I already managed to get internal ADDRESS of the instance, which is unique until the garbage collector (GC) compacts the heap (= moves the objects = changes the addresses).</p>
  
  <p>Stack&nbsp;Overflow question <em><a href="https://stackoverflow.com/questions/720177/default-implementation-for-object-gethashcode">Default implementation for Object.GetHashCode()</a></em> might be related.</p>
  
  <p>The objects are not under my control as I am accessing objects in a program being debugged using the debugger API. If I was in control of the objects, adding my own unique identifiers would be trivial.</p>
  
  <p>I wanted the unique ID for building a hashtable ID -> object, to be able to lookup already seen objects. For now I solved it like this:</p>
  
  <pre><code>Build a hashtable: 'hashCode' -&gt; (list of objects with hash code == 'hashCode')
  Find if object seen(o) {
      candidates = hashtable[o.GetHashCode()] // Objects with the same hashCode.
      If no candidates, the object is new
      If some candidates, compare their addresses to o.Address
          If no address is equal (the hash code was just a coincidence) -&gt; o is new
          If some address equal, o already seen
  }
  </code></pre>