the IComparer
interfaces (both the generic and the non-generic one) allow you to compare two instances with each other.
The Compare
method allows you to compare an object itself with another instance. Offcourse, when the current instance is null, you'll get a NullReferenceException
in this case, since you call Compare
on a 'null' instance. A class that implements IComparer
can overcome this problem.
So, when you implement the IComparer interface, you'll have a class which has a 'Compare' method, which can be called like this:
public class MyObjectComparer : IComparer<MyObject>
{
public int Compare( MyObject first, MyObject second )
{
// implement logic here to determine whether first is less, greater or equal then second.
}
}
This allows you to do this:
var c = new MyObjectComparer();
var one = new MyObject();
var two = new MyObject();
c.Compare (one, two);
When you instantiate a Hashtable
with the constructor where you specify the IEqualityComparer
instance, this means that the given IEqualityComparer
will be used to determine whether a certain key is already present in the Hashtable.
Otherwise, the Compare method of the key-object will be used.