title: How to use custom object as dictionary key?
body: <p>I want to create a <code>Dictionary&lt;Coordinate, Status&gt;</code>, but the key is always equals to <code>&quot;Bot.Core.Games.Coordinate&quot;</code>.</p>
  <h2>Classes</h2>
  <p><strong>Coordinate</strong></p>
  <pre><code>public class Coordinate
  {
      public int x { get; set; }
      public int y { get; set; }
  }
  </code></pre>
  <p><strong>Status</strong></p>
  <pre><code>public class Enums
  {
      public enum Status { UNCAPTURED, PLAYER1, PLAYER2, WIN }
  }
  </code></pre>
  <hr />
  <h2>First try</h2>
  <pre><code>Dictionary&lt;Coordinate, Status&gt; Fields { get; set; } = new Dictionary&lt;Coordinate, Status&gt;()
  {
      {new Coordinate() { x = 0, y = 0 }, Status.UNCAPTURED}
  }
  </code></pre>
  <h2>Second try</h2>
  <p>I did some research and I found this: <a href="https://stackoverflow.com/questions/6999191/use-custom-object-as-dictionary-key">Use custom object as Dictionary Key</a> <br>
  So the code now looks like this:</p>
  <pre><code>public class Coordinate
  {
      public int x { get; set; }
      public int y { get; set; }
  
      public bool Equals(Coordinate coordinate) =&gt; coordinate.x.Equals(x) &amp;&amp; coordinate.y.Equals(y);
      public bool Equals(object o) =&gt; Equals(o as Coordinate);
      public override int GetHashCode() =&gt; x.GetHashCode() ^ y.GetHashCode();
  }
  </code></pre>
  <h2>Third try</h2>
  <p>Since none of the previously tried code works I did more research and found <a href="https://social.msdn.microsoft.com/Forums/vstudio/en-US/41fd15a3-6fda-4855-afe5-73498fd1a067/example-of-dictionary-collection-with-custom-class-as-key?forum=netfxbcl" rel="nofollow noreferrer">this</a>.<br>So now the code is:</p>
  <pre><code>public class Coordinate
  {
      public int x { get; set; }
      public int y { get; set; }
  
      public class CoordinateEqualityComparer : IEqualityComparer&lt;Coordinate&gt;
      {
          public bool Equals(Coordinate a, Coordinate b) =&gt; ((a.x == b.x) &amp; (a.y == b.y));
  
          public int GetHashCode(Coordinate obj)
          {
              string combined = obj.x + &quot;|&quot; + obj.y;
              return (combined.GetHashCode());
          }
      }
  }
                                                                                 
  Dictionary&lt;Coordinate, Status&gt; Fields { get; set; } = new Dictionary&lt;Coordinate, Status&gt;(new Coordinate.CoordinateEqualityComparer())
  {
       {new Coordinate() { x = 0, y = 0 }, Status.UNCAPTURED}
  }
  </code></pre>
  <p>The key is always <code>&quot;Bot.Core.Games.Coordinate&quot;</code>. How to fix this?</p>