Archive for March, 2012
IDictionary : Using custom class as key
I was using IDictionary
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
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
var d = new Dictionary<KeyClass, ValueClass>(new KeyClass.EqualityComparer());
Things worked fine afterwards.