Archive for March, 2012

IDictionary : Using custom class as key

I was using IDictionary in one of my projects. The KeyClass is very simple containing just two integers.

public class KeyClass
{
    public int ValueA{get;set;}
    public int ValueB{get;set;}
}

I was accessing values from dictionary like follows:

var k = new KeyClass(1, 1);
var v = myDictionary[k];

The dictionary for sure contained KeyClass key with ValueA = 1 and ValueB = 1 and simillarly many other keys. But I got exception:

The given key is not present in the dictionary.
I implemented IComparable in class KeyClass but it did not solve my problem. I googled and found this CodeProject article. It describes following technique to use a class implementing IEqualityComparer interface. I defined it in my class:

public class KeyClass
{
    public int ValueA{get;set;}
    public int ValueB{get;set;}

    public class EqualityComparer : IEqualityComparer<KeyClass>
    {
        public bool Equals(KeyClass a, KeyClass b)
        {
            return a.ValueA == b.ValueA && a.ValueB == b.ValueB;
        }

        public int GetHashCode(KeyClass k)
        {
            return k.ValueA ^ k.ValueB;
        }
    }
}

Now I have to declare IDictionary as follows:

var d = new Dictionary<KeyClass, ValueClass>(new KeyClass.EqualityComparer());

Things worked fine afterwards.

No Comments