Reputation: 3625
Can anyone help explain the following. I am having an issue with a Dictionary where ContainsKey
evaluates to false while both Equals
and GetHashCode
for the objects are successful. Below is the output from the immediate window in Visual Studio:
?LocationToRackingGroup.Keys.ToArray()[23].Equals(location)
true
?LocationToRackingGroup.Keys.ToArray()[23] == (location)
true
?this.LocationToRackingGroup.ContainsKey(location)
false
Am I missing something? Any ideas are much appreciated.
Upvotes: 2
Views: 289
Reputation: 11808
OK, this is a long shot.
In the first two lines you refer to LocationToRackingGroup
and in the last to this.LocationToRackingGroup
, are they the same variable?
Upvotes: 1
Reputation: 117320
The rule is that the hashcode must be the same for every 'instance' of the same data. If it changes, then your hash function is broken.
IOW, the safest hash function is:
int GetHashcode()
{
return 0;
}
Upvotes: 0
Reputation: 1063864
Well, I'd want to look at a couple of things:
1: is GetHashCode
correctly implemented:
?LocationToRackingGroup.Keys.ToArray()[23].GetHashCode() == location.GetHashCode()
2: if this is the generic dictionary, does the type also implement (explicitly) IEquatable<Location>
3: did you supply a custom IEqualityComparer<Location>
to the dictionary in the constructor?
To rule out the last, perhaps look at:
?LocationToRackingGroup.Comparer.Equals(blah23, location); // should be true
?LocationToRackingGroup.Comparer.GetHashCode(blah23); // should equal below
?LocationToRackingGroup.Comparer.GetHashCode(location);// should equal above
Upvotes: 3
Reputation: 4314
Is location mutable? Because if it is, it might have changed since you put it into the dictionary.
Upvotes: 6