Sunday, March 19, 2006 - Posts

IKeyComparer?

The preperation guide for 70-536 Microsoft .NET Framework 2.0 - Application Development Foundation points to the IKeyComparer and the IHashCodeProvider interfaces as fundamentals you should be proficient with before taking the test. There is no such thing as an IKeyComparer interface in the .NET Framework 2.0 - the interface was removed after beta 1. The IHashCodeProvider interface has been marked obsolete in .NET 2.0 and you should use the IEqualityComparer interface instead.

The beta 1 design of the IComparer interface grouped all comparison related methods into a single interface to avoid a common design fault from .NET 1.1, where one could pass an incompatible pair of IComparer and IHashCodeProvider to the Hashtable constructor. After shipping beta 1 of .NET 2.0, Microsoft split their original IComparer interface into the IEqualityComparer and a new definition of IComparer after realizing that the new design introduced incompatabilies with classes that currently didn’t implent IComparable and that the IComparable.CompareTo(T) method required types to have natural ordering.

The IKeyComparer was in essence both an IHashCodeProvider and an IComparer that was intended to be used to compare dictionary keys based on hashcode equality, thus avoiding the .NET 1.1 scenario where one could pass an IHashCodeProvider that considered two instances equal along with an IComparer that considered the same instances as inequal making the Hashtable indexer fail to find a value with a given key.
You might also have heard of an interface called IHashComparer. This was a proposed name for the IKeyComparer interface during the beta 2 refactoring, but this interface was not included in the final release of .NET 2.0.

The one interface you should know is IEqualityComparer. This is a special interface that should only be used for determining equality, and not for sorting. The interface is particularly handy for culture aware comparisons such as determing that the German words ”weiss” and ”weiß” are the same.