Custom dictionary keys identity

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.



Answer this question

Custom dictionary keys identity

  • Sguillo

    Chris,

    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.

    hey Chris,

    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

    You were absolutely right.
    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.

    Code Snippet

    // Override the Equal check

    public override bool Equals (object o)

    {

    if (o != null && GetType() == o.GetType())

    {

    if (this.ToString() == o.ToString())

    return true;

    }

    return false;

    }

    // Override the Unique hashcode for the object

    public override int GetHashCode()

    {

    return this.someUniqueInteger;

    }


  • JMiguel

    Chris,

    I'm having the same issue. do you happen to have a code sample on how to do this override

    Thanks,

    Frank


  • Custom dictionary keys identity