GetHashCode in IEqualityComparer - C#

Shervan360 1,661 Reputation points
2023-01-03T14:32:49.687+00:00

Happy New Year.

I understood why we should have the Equals method with two arguments. We compare two objects each time.
But I don't understand the GetHashCode method. Why does it have one argument? We are comparing two objects.
How do they work? In each comparison, one method has two arguments for comparing two objects, one method has one argument.
What is going on behind the scenes?

internal class Student  
{  
    public int StudentID { get; set; }  
    public int Age { get; set; }  
    public string StudentName { get; set; }  
    public int StandardID { get; set; }  
}  
class EqualityBasedStudent : IEqualityComparer<Student>  
{  
    public bool Equals(Student s1, Student s2)  
    {  
        if (s1.StudentName.CompareTo(s2.StudentName) == 0)  
            if (s1.StudentID.CompareTo(s2.StudentID) == 0)  
                return true;  
        return false;  
  
    }  
    public int GetHashCode(Student s1)  
    {  
        return s1.StudentID.GetHashCode();  
    }  
}  
Developer technologies C#
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-01-04T07:19:46.237+00:00

    @Shervan360 , Welcome to Microsoft Q&A, based on your description, you want to know how the GetHashCode work in IEqualityComparer.

    The GetHashCode method is used to generate an address where the object is stored. So, a dictionary doesn't have to search for it. It just computes the Hash code and jumps to that location. The Equals method is a better test of equality but cannot be used to map an object into an address space.

    The answer has a good example and enough explanation for it and you could have a look.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.