- Home /
Question by
AshleyJamesy · Nov 01, 2016 at 06:40 AM ·
classclassesdictionarycollectionscollection
Cannot use custom type as key for dictionary
Can someone explain why this isn't working?
public class GridCoordinates
{
public GridCoordinates(int _x, int _y)
{
m_X = _x;
m_Y = _y;
}
public int m_X = 0;
public int m_Y = 0;
}
void Check(GridCoordinates _coordinates)
{
//Dictionary<GridCoordinates, Object>
_Map.Add(new GridCoordinates(_coordinates.m_X, _coordinates.m_Y), new Object());
if (_Map.ContainsKey(_coordinates))
Debug.Log("Success");
else
Debug.Log("Fail");
}
Is it to do with the dictionary checking the key as a reference?
Comment
I think you are doing it right!
But you created an new GridCoords, so if you try to compare with the referenced one, you'll get an Fail.
So I gues:
_$$anonymous$$ap.Add(_coordinates), new Object());
will work.
Have ou tried implementing the IEquatable interface?
Example from my own Coordinate class (it doesn't matter if it's a struct or a class):
public struct Coordinate3 : IEquatable<Coordinate3> {
public int x;
public int y;
public int z;
public Coordinate3(int a, int b, int c) {
x = a;
y = b;
z = c;
}
public bool Equals(Coordinate3 other) {
if (this.x == other.x && this.y == other.y && this.z == other.z) {
return true;
}
else {
return false;
}
}
public override int GetHashCode() {
return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode();
}
}
Your answer
Follow this Question
Related Questions
OrderedDictionary in System.Collections.Generic for mobile 0 Answers
Can a class hear a broadcast message? 0 Answers
How can I use method to return custom classes (Same Class Type),How to return classes in method 1 Answer
Saving dictionary from editor mode in play mode 1 Answer
How to refer to object based on value of a variable 1 Answer