Tuesday, June 23, 2009

Complex Keys In Generic Dictionary

Let us start with the quiz about generic dictionary.

Dictionary simpleDict = new Dictionary(StringComparer.OrdinalIgnoreCase);
simpleDict["name1"] = "value";
simpleDict["Name1"] = "value2";
What value will simpleDict["name1"] return?

Let's get back to using complex keys in generic dictionary.

.NET Framework provides IEqualityComparer<T> interface that can be used by dictionary to distinguish between different keys.

Imagine we have a complex class that we want to serve as a key in our dictionary.
public class ComplexKey
{
public int Part1 { get; set; }
public string Part2 { get; set; }
}
The implentation of the comparer will be the following:
public class ComplexKeyComprarer : IEqualityComparer
{
public bool Equals(ComplexKey x, ComplexKey y)
{
return x.Part1.Equals(y.Part1) && x.Part2.Equals(y.Part2);
}

public int GetHashCode(ComplexKey obj)
{
return obj.Part1.GetHashCode() ^ obj.Part2.GetHashCode();
}
}
Having created the comparer we can now instantiate dictionary and operate with complex keys in the same way as with simple ones.
Dictionary<ComplexKey, string> complexDict = 
new Dictionary<ComplexKey, string>(new ComplexKeyComprarer());

ComplexKey ck1 = new ComplexKey() { Part1 = 1, Part2 = "name1" };
ComplexKey ck2 = new ComplexKey() { Part1 = 1, Part2 = "name2" };

complexDict[ck1] = "value1";
complexDict[ck2] = "value2";

Very convenient by the way :)