I want to create a Dictionary<Coordinate, Status>
, but the key is always equals to "Bot.Core.Games.Coordinate"
.
Classes
Coordinate
public class Coordinate
{
public int x { get; set; }
public int y { get; set; }
}
Status
public class Enums
{
public enum Status { UNCAPTURED, PLAYER1, PLAYER2, WIN }
}
First try
Dictionary<Coordinate, Status> Fields { get; set; } = new Dictionary<Coordinate, Status>()
{
{new Coordinate() { x = 0, y = 0 }, Status.UNCAPTURED}
}
Second try
I did some research and I found this: Use custom object as Dictionary Key
So the code now looks like this:
public class Coordinate
{
public int x { get; set; }
public int y { get; set; }
public bool Equals(Coordinate coordinate) => coordinate.x.Equals(x) && coordinate.y.Equals(y);
public bool Equals(object o) => Equals(o as Coordinate);
public override int GetHashCode() => x.GetHashCode() ^ y.GetHashCode();
}
Third try
Since none of the previously tried code works I did more research and found this.
So now the code is:
public class Coordinate
{
public int x { get; set; }
public int y { get; set; }
public class CoordinateEqualityComparer : IEqualityComparer<Coordinate>
{
public bool Equals(Coordinate a, Coordinate b) => ((a.x == b.x) & (a.y == b.y));
public int GetHashCode(Coordinate obj)
{
string combined = obj.x + "|" + obj.y;
return (combined.GetHashCode());
}
}
}
Dictionary<Coordinate, Status> Fields { get; set; } = new Dictionary<Coordinate, Status>(new Coordinate.CoordinateEqualityComparer())
{
{new Coordinate() { x = 0, y = 0 }, Status.UNCAPTURED}
}
The key is always "Bot.Core.Games.Coordinate"
. How to fix this?