I implemented a reference class (MyKey) that I use as key of a dictionary (Generic.Dictionary<MyKey, MyValue>). The problem is that ContainsKey always returns false, except when I pass the very object that I used as key.
I tried to override Object.Equals: no change
I then tried to implement IComparable, then IEquatable<MyKey>: still no change
What should MyKey implement for this to work
Chris.

Custom dictionary keys identity
Sguillo
I looked up the method Dictionary.ContainsKey in reflector and looks like it's doing a couple of things: Besides calling the the Equals method for comparison, it is also comparing the hashcodes (which it's getting using GetHashCode). So, here's what I believe is happening: if you've not overriden Object's GetHashCode, the two instances would have different hashcodes and the comparison would fail. You can try overriding the GetHashCode for MyKey and see if that works.
hope that helps,
Imran.
Alex.P.
you can get the tool Reflector from http://www.aisto.com/roeder/dotnet/. You can load up assemblies and look at the implementations of various types. I can't say enough about this tool. You should definitely get it.
Imran.
danny_ward
Thanks a lot !
When you say that you "looked up the method Dictionary.ContainsKey in reflector", what do you mean In previous versions of Visual Studio I was able to debug into the generics source code but it is no longer the case. Is there still some way to have access to the implementation of generics
Chris.
raluca
Hi,
Thanks.. I had the exact same issue with using a generic Dictionary<>. I solved my issue by overriding the Equals AND GetHashCode() methods.
// Override the Equal check
public override bool Equals (object o)
{
}
// Override the Unique hashcode for the object
public override int GetHashCode()
{
}
JMiguel
Chris,
I'm having the same issue. do you happen to have a code sample on how to do this override
Thanks,
Frank