BlackWaspTM
.NET Framework
.NET 2.0+

Implementing IEqualityComparer<T> (2)

IEqualityComparer<T> is a generic interface defined in the .NET framework version 2.0 and used in many standard classes, including several LINQ operators. The interface can be implemented to allow customised comparison of values and objects.

Implementing Equals

Let's continue implementing the interface for our CustomerComparer class. We'll add the Equals method next. As we only care about the two ID values being the same, the method can return the result of a comparison of the two globally unique identifiers (GUIDs). Add the code shown below to the class:

public bool Equals(Customer customer1, Customer customer2)
{
    return customer1.Id == customer2.Id;
}

Implementing GetHashCode

We now need to implement the GetHashCode method. We can't return the hash code of the Customer object as this will vary for Customers that we want to be equal. However, as we are only comparing the IDs, we can return the hash code of the customer's ID property.

public int GetHashCode(Customer customer)
{
    return customer.Id.GetHashCode();
}

Testing the Comparer

We can test the CustomerComparer class by creating several Customers and comparing them. The code below instantiates three customers. The first two have matching IDs so comparing them generates a true result and both have the same hash code when obtained via the comparer. The third customer has the same name as the first but a different ID. This means that the comparison of the first and third customers returns false and the two objects' hash codes differ.

Customer customer1 = new Customer();
customer1.Id = new Guid("12345678901234567890123456789012");
customer1.Forename = "Bob";

Customer customer2 = new Customer();
customer2.Id = new Guid("12345678901234567890123456789012");
customer2.Surname = "Smith";

Customer customer3 = new Customer();
customer3.Id = new Guid("11111111111111111111111111111111");
customer3.Forename = "Bob";

CustomerComparer comparer = new CustomerComparer();

bool same1and2 = comparer.Equals(customer1, customer2);  // true
bool same1and3 = comparer.Equals(customer1, customer3);  // false

int hash1 = comparer.GetHashCode(customer1);             // -1876532676
int hash2 = comparer.GetHashCode(customer2);             // -1876532676
int hash3 = comparer.GetHashCode(customer3);             // 285212689
14 January 2012