Dictionary, IEquatable, Equals and GetHashCode

The docs for the .NET Dictionary class lead you to believe that implementing IEquatable for a dictionary key is good enough to get the dictionary to use your Equals method.  However, one must also override GetHashCode.  Given the way a dictionary works, this is logical but not documented.  The interesting part, is that the Remove method on the dictionary will use your Equals with or without GetHashCode being implemented.  In this way, you can add identical items and remove more than one with one remove.  Not that you’d want to.  Anyway, this class will work as a dictionary key:

public class MyDickKey : IEquatable<MyDickKey>
    private string m_comparableString;
    private string ComparableString
    { get {
        return (m_comparableString != null ?
            m_comparableString : GenComparableString()); } }
    private void ResetComparableString()
        { m_comparableString = null; }
    private string GenComparableString()
        {/*m_comparableString = something */}
    public MyDickKey() { }
    public bool Equals(MyDickKey rhs)
        return this.ComparableString.Equals(rhs.ComparableString);
    public override int GetHashCode()
        return ComparableString.GetHashCode();


2 thoughts on “Dictionary, IEquatable, Equals and GetHashCode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s