GetHashCode problem

Can anyone help explain the following. I have a problem with Dictionary where it ContainsKey

evaluates to false Equals

and GetHashCode

for objects it is successful. Below is the output from the direct 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 greatly appreciated.

+2


source to share


4 answers


Has the location changed? Because if so, it might have changed since you put it in the dictionary.



+6


source


Ok, I would like to look at a couple of things:

1: GetHashCode

correctly implemented:

?LocationToRackingGroup.Keys.ToArray()[23].GetHashCode() == location.GetHashCode()

      

2: if it's a generic vocabulary, does the type implement (explicitly) IEquatable<Location>



3: did you add the custom one IEqualityComparer<Location>

to the dictionary in the constructor?

To rule out the latter, 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

      

+3


source


OK, this is a long shot.

In the first two lines you refer to LocationToRackingGroup

and in the last case to this.LocationToRackingGroup

, are they the same variable?

+1


source


The rule of thumb is that the hash code must be the same for every "instance" of the same data. If it changes, your hash function will be broken.

IOW, the safest hash function:

int GetHashcode()
{
  return 0;
}

      

0


source







All Articles