title: How do I obtain an ID that allows me to tell difference instances of a class apart?
body: <p>Imagine I have a single class, with two instances:</p>
  
  <pre><code>MyClass a = new MyClass();
  MyClass b = new MyClass();
  </code></pre>
  
  <p>MyClass has a method PrintUniqueInstanceID:</p>
  
  <pre><code>void PrintUniqueInstanceID()
  {
    Console.Write("Unique ID for the *instance* of this class: {0}", 
        [what goes here???]
    );
  }
  </code></pre>
  
  <p>Ideally, the output would be something like:</p>
  
  <pre><code>Unique ID for the *instance* of this class: 23439434        // from a.PrintUniqueInstanceID
  Unique ID for the *instance* of this class: 89654           // from b.PrintUniqueInstanceID
  </code></pre>
  
  <p>So - what would I insert in "<code>[what goes here???]</code>", above, which prints a unique number for every unique instance of the class?</p>
  
  <p><strong>Ideas</strong></p>
  
  <ol>
  <li>Perhaps cast "this" to an int pointer, and use that?</li>
  <li>Use GCHandle somehow? </li>
  <li>Access a property of "this", within the method, to uniquely identify it?</li>
  </ol>
  
  <p><strong>(optional) Background Information For Experts</strong></p>
  
  <p>The reason I need this is that I am using AOP and PostSharp to automatically detect threading issues. I need to look up each unique instance of the class in a dictionary, in order to verify that multiple threads are not accessing the same unique instance of a class (its ok if there is one thread per class instance).</p>
  
  <p><strong>Update</strong></p>
  
  <p>As others have pointed out, I should mention that I can't touch any of the existing classes in the 30,000 line project. PrintUniqueInstanceID, above, is an aspect (see <a href="http://www.sharpcrafters.com/">PostSharp</a>) that is added to the top level class, is inherited by every class in the entire project, and executes on every method entry in the entire project.</p>
  
  <p>Once I have verified that everything is thread safe, I'll remove the aspect to restore performance.</p>