DEV Community

Cover image for C# - Implementing a Custom Equality Comparer
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Implementing a Custom Equality Comparer

In C#, you can customize how objects are compared for equality by implementing a custom equality comparer. This allows you to define your own criteria for comparing objects beyond the default behavior of reference equality or value equality.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a list of Person objects
        var people = new List<Person>
        {
            new Person { Id = 1, Name = "John" },
            new Person { Id = 2, Name = "Alice" },
            new Person { Id = 3, Name = "Bob" }
        };

        // Create a custom equality comparer based on the Id property
        var idEqualityComparer = new IdEqualityComparer();

        // Use the custom equality comparer to find a person by Id
        var personToFind = new Person { Id = 2, Name = "Unknown" };
        var foundPerson = people.Find(p => idEqualityComparer.Equals(p, personToFind));

        if (foundPerson != null)
        {
            Console.WriteLine($"Found person: {foundPerson.Name}");
        }
        else
        {
            Console.WriteLine("Person not found.");
        }
    }
}

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class IdEqualityComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (x is null || y is null) return false;
        return x.Id == y.Id;
    }

    public int GetHashCode(Person obj)
    {
        if (obj is null) return 0;
        return obj.Id.GetHashCode();
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We have a Person class with an Id property and a Name property.

  2. We create a list of Person objects representing a collection of people.

  3. We implement a custom equality comparer class IdEqualityComparer that implements the IEqualityComparer<Person> interface.

  4. The Equals method in the custom equality comparer compares Person objects based on their Id property. If the Id values match, the objects are considered equal.

  5. The GetHashCode method is implemented to generate a hash code based on the Id property for hash-based data structures like dictionaries.

  6. We use the custom equality comparer to find a person in the list based on their Id property. This allows us to find a specific person by their Id even if the reference to the Person object is different.

By implementing a custom equality comparer, you can tailor the equality comparison logic to your specific needs, making it easier to work with complex objects and custom data structures.

Top comments (0)