C# - IEqualityComparer
IEqualityComparer<T>
is an interface in C# that allows you to create custom logic for determining the equality of two objects of a specified type T
and for retrieving hash codes for objects of that type. It provides greater flexibility than the default equality comparison mechanism in .NET.
The IEqualityComparer<T>
interface has two primary methods:
bool Equals(T x, T y)
: This method determines whether two objects are equal.
int GetHashCode(T obj)
: This method returns a hash code for an object.
Example:
Imagine you have a Person
class, and you want to compare two Person
objects based on their Name
property, ignoring their age.
using System;
using System.Collections.Generic;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class PersonNameEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (x == null || y == null)
return false;
return x.Name.Equals(y.Name, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(Person obj)
{
if (obj == null)
return 0;
return obj.Name?.GetHashCode() ?? 0;
}
}
public class Program
{
public static void Main()
{
Person person1 = new Person { Name = "John", Age = 25 };
Person person2 = new Person { Name = "john", Age = 30 };
var comparer = new PersonNameEqualityComparer();
if (comparer.Equals(person1, person2))
{
Console.WriteLine("The two persons have the same name.");
}
else
{
Console.WriteLine("The two persons have different names.");
}
}
}
In the above example:
- We've defined a
Person
class with Name
and Age
properties.
- We've created an
IEqualityComparer
implementation named PersonNameEqualityComparer
. This comparer checks the equality of persons based solely on their Name
property, ignoring case differences.
- In the
Main
method, we've created two Person
instances with different ages but the same name (with different case). Using our custom comparer, we determine that they are considered equal by name.
When running this program, the output will be:
The two persons have the same name.
This demonstrates how IEqualityComparer<T>
allows for custom equality comparisons beyond the default behavior provided by .NET.