title: How does HashSet compare elements for equality?
body: <p>I have a class that is <code>IComparable</code>:</p>
  
  <pre><code>public class a : IComparable
  {
      public int Id { get; set; }
      public string Name { get; set; }
  
      public a(int id)
      {
          this.Id = id;
      }
  
      public int CompareTo(object obj)
      {
          return this.Id.CompareTo(((a)obj).Id);
      }
  }
  </code></pre>
  
  <p>When I add a list of object of this class to a hash set:</p>
  
  <pre><code>a a1 = new a(1);
  a a2 = new a(2);
  HashSet&lt;a&gt; ha = new HashSet&lt;a&gt;();
  ha.add(a1);
  ha.add(a2);
  ha.add(a1);
  </code></pre>
  
  <p>Everything is fine and <code>ha.count</code> is <code>2</code>, but:</p>
  
  <pre><code>a a1 = new a(1);
  a a2 = new a(2);
  HashSet&lt;a&gt; ha = new HashSet&lt;a&gt;();
  ha.add(a1);
  ha.add(a2);
  ha.add(new a(1));
  </code></pre>
  
  <p>Now <code>ha.count</code> is <code>3</code>.</p>
  
  <ol>
  <li>Why doesn't <code>HashSet</code> respect <code>a</code>'s <code>CompareTo</code> method.</li>
  <li>Is <code>HashSet</code> the best way to have a list of unique objects?</li>
  </ol>