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:
- The type used as the key has overridden methods for GetHashCode and Equals.
- The dictionary is constructed as new Dictionary() with no extra constructor arguments.
- By debugging, I've verified that GetHashCode in the key type is called, but not Equals(obj)
- When the application runs, there's only one DLL loaded that has the key type, so it's probably not a case of the same type in different versions of the same DLL
Does anyone know why this might be occuring?
Thanks for any help - I'm running out of ideas here.