Reputation: 1056
This is in C#. I have a problem whereby Dictionary.ContainsKey returns false even though I know the key to be in there.
I don't have any code to show unfortunately. The code is not easy to pull together; it is spread across multiple classes and triggered through events and so on. A quick unit test I wrote didn't reproduce the problem.
Here is the output of the immediate window during a debugging session (added comments and changed to protect details):
// throws KeyNotFoundException
myDict[key]
// throws KeyNotFoundException
myDict[new MyKey("SomeString .1", "SomeOtherString", SomeEnum.Foo)]
// Element [5] is the key
myDict.Keys
Count = 10
[0]: {...}
[1]: {...}
[2]: {...}
[3]: {...}
[4]: {...}
[5]: {Foo SomeOtherString SomeString .1}
[6]: {...}
[7]: {...}
[8]: {...}
[9]: {...}
// Get key at element [5]
enumerator.Current
{Foo SomeOtherString SomeString .1}
[My.Namespace.KeyType]: {Foo SomeOtherString SomeString .1}
SomeEnum: Foo
SomeOtherStringProperty: "SomeOtherString"
// key used to do lookup
key
{Foo SomeOtherString SomeString .1}
[My.Namespace.KeyType]: {Foo SomeOtherString SomeString .1}
SomeEnum: Foo
SomeOtherStringProperty: "SomeOtherString"
// hash codes of key in dictionary matches hash code of lookup key
enumerator.Current.GetHashCode()
193014103
key.GetHashCode()
193014103
Some extra notes:
Does anyone know why this might be occuring?
Thanks for any help - I'm running out of ideas here.
Upvotes: 3
Views: 574
Reputation: 19496
The type used as the key has overridden methods for GetHashCode and Equals.
This is the first thing that I would check. If the hash code is based on a mutable value, it could definitely cause this problem.
From MSDN:
In general, for mutable reference types, you should override GetHashCode only if:
You can compute the hash code from fields that are not mutable; or
You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
Otherwise, you might think that the mutable object is lost in the hash table. If you do choose to override GetHashCode for a mutable reference type, your documentation should make it clear that users of your type should not modify object values while the object is stored in a hash table.
Upvotes: 5