title: Using a class versus struct as a dictionary key
body: <p>Suppose I had the following class and structure definition, and used them each as a key in a dictionary object:</p>
  
  <pre><code>public class MyClass { }
  public struct MyStruct { }
  
  public Dictionary&lt;MyClass, string&gt; ClassDictionary;
  public Dictionary&lt;MyStruct, string&gt; StructDictionary;
  
  ClassDictionary = new Dictionary&lt;MyClass, string&gt;();
  StructDictionary = new Dictionary&lt;MyStruct, string&gt;();
  </code></pre>
  
  <p>Why is it that this works:</p>
  
  <pre><code>MyClass classA = new MyClass();
  MyClass classB = new MyClass();
  this.ClassDictionary.Add(classA, "Test");
  this.ClassDictionary.Add(classB, "Test");
  </code></pre>
  
  <p>But this crashes on runtime:</p>
  
  <pre><code>MyStruct structA = new MyStruct();
  MyStruct structB = new MyStruct();
  this.StructDictionary.Add(structA, "Test");
  this.StructDictionary.Add(structB, "Test");
  </code></pre>
  
  <p>It says the key already exists, as expected, but only for the struct. The class treats it as two separate entries. I think it has something to do with the data being held as a reference versus value, but I would like a more detailed explanation as to why.</p>