I’m trying to make a custom container to use as a dict key, so I can index values by an int and string instead of by one key. The intended usage is pretty simple:
public class CalendarKey
{
public int myDayOfYear;
public TimeOfDay myTimeOfDay;
}
public void TestStructDict()
{
CalendarKey keyA = new CalendarKey();
keyA.myDayOfYear = 1;
keyA.myTimeOfDay = TimeOfDay.Afternoon;
CalendarKey keyB = new CalendarKey();
keyB.myDayOfYear = 1;
keyB.myTimeOfDay = TimeOfDay.Afternoon;
Dictionary<CalendarKey, string> testDict = new Dictionary<CalendarKey, string>();
testDict.Add(keyA, "Key A");
Debug.Log(testDict[keyA]);
Debug.Log(testDict[keyB]);
}
My expectation is for testDict[keyA] and testDict[keyB] to return the same data, since structs are value types, not reference types, but testDict[keyB] returns a key not found exception. I thought this might mean that I need to manually add a comparison operator:
public class CalendarKey
{
public int myDayOfYear;
public TimeOfDay myTimeOfDay;
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
CalendarKey key = (CalendarKey)obj;
if (key == null)
{
return false;
}
return myDayOfYear == key.myDayOfYear && myTimeOfDay == key.myTimeOfDay;
}
}
However, this has no effect, and the error persists- is it simply not possible (or at least recommended) to use structs as dict keys, or am I doing something else wrong here?