I have a class that essentially wraps a string so that I can make a custom editor for this class easily. I want this class to act as if it is a string when comparing to other classes. I am using this class as a key in a Dictionary, yet when using the TryGetKey method it returns false even when both TilemapID’s id strings are the same.
This is what I have:
[System.Serializable]
public sealed class TilemapID
{
public static readonly string[] ID_LIST = new string[] { "base", "foreground", "background" };
public string id;
public TilemapID(string id)
{
this.id = id;
}
public override string ToString()
{
return id;
}
public override int GetHashCode()
{
return id.GetHashCode();
}
public override bool Equals(object obj)
{
return id.Equals(obj);
}
public static explicit operator string(TilemapID id) => id.id;
public static explicit operator TilemapID(string s)
{
for (int i = 0; i < ID_LIST.Length; i++)
{
if (ID_LIST[i].Equals(s))
return new TilemapID(ID_LIST[i]);
}
return null;
}
}
I can verify through the Visual Studio Debugger that both this "id" and another TilemapID’s "id" are the same:
Both maps[q].id & savedTiles[0].id are the same.
I’ve tried to step through visual studio with the debugger, and when it gets to the part shown in the screenshot it goes to the GetHashCode method, then the Equals method, which returns false, so it skips over grabbed = g and goes to else continue. Shouldn’t it actually go to grabbed = g because I overrode the Equals and GetHashCode methods, which should return true?
>Solution :
You are overriding the Equals method, you should be doing the equality check yourself then.
public override bool Equals(object obj)
{
if(obj is not TilemapID tm) return false;
return tm.id == id;
}