- Home /
Why isn't my operator override working on structs?
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?
I think that's because its comparing its references. Did you try creating dictionary with custom comparer? https://msdn.microsoft.com/en-us/library/ms132072(v=vs.110).aspx 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
Answer by cgarossi · Aug 04, 2017 at 02:10 PM
You are overriding the method Equals() not the actual = operator.
Use
return myDayOfYear.Equals(key.myDayOfYear) && myTimeOfDay.Equals(key.myTimeOfDay);
Here's some info on actual operator overloading
https://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx
Ooh that's really helpful, thank you for clarifying! :)
Your answer
Follow this Question
Related Questions
Comparing string to a dictionary entry? 0 Answers
importing english dictionary as text file? 1 Answer
String comparison, can't use false result as string. 4 Answers
Should I use == to compare boolean in an if statement? 1 Answer
Unity enum map - how to make it more efficient/clean? Linear line complexity. Best practices. 1 Answer