title: How does c# figure out the hash code for an object?
body: <p>This question comes out of the discussion on <a href="https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c">tuples</a>.</p>
  
  <p>I started thinking about the hash code that a tuple should have. 
  What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure.</p>
  
  <p>Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary.</p>
  
  <p>But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class!</p>
  
  <p>How does it work? What's the analysis made by Object.GetHashCode()? </p>
  
  <p>Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still)</p>
  
  <p>Consider this code as an example:</p>
  
  <pre><code>namespace csharp_tricks
  {
      class Program
      {
          class MyClass
          {
              int keyValue;
              int someInfo;
  
              public MyClass(int key, int info)
              {
                  keyValue = key;
                  someInfo = info;
              }
  
              public override bool Equals(object obj)
              {
                  MyClass other = obj as MyClass;
                  if (other == null) return false;
  
                  return keyValue.Equals(other.keyValue);
              }
  
              public override int GetHashCode()
              {
                  return keyValue.GetHashCode();
              }
          }
  
          static void Main(string[] args)
          {
              Dictionary&lt;object, object&gt; dict = new Dictionary&lt;object, object&gt;();
  
              dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 1), 1), 1);
  
              //here we get the exception -- an item with the same key was already added
              //but how did it figure out the hash code?
              dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 2), 1), 1); 
  
              return;
          }
      }
  }
  </code></pre>
  
  <p><strong>Update</strong> I think I've found an explanation for this as stated below in my answer. The main outcomes of it are:</p>
  
  <ul>
  <li>Be careful with your keys and their hash codes :-)</li>
  <li>For complicated dictionary keys you must override Equals() and GetHashCode() correctly.</li>
  </ul>