DEV Community

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

Posted on

4

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.

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay