Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overridden Equals method not getting called by HashSet [duplicate]

Tags:

c#

I have a class named 'x' which overrrides Equals() as follows:

    public override bool Equals(object obj)
    {
        if(obj is x)
        {
            return ((obj as x).key == this.key);
        }
        return false;
    }

When the following extension method tries to use the above override for comparison, Equals() doesnt get used:

    public static bool Contains(this HashSet<x> set, char key)
    {
        x SearchKey = new x(key);
        return set.Contains(SearchKey);
    }

I get the expected behavior only when I modify the first line in the extensio method as follows:

x SearchKey = new x(key);

Can you please explain this behavior?

I had expected that, Equals() would get called against instance of x itself since it is a subset of Object. What am I missing?

like image 849
Aadith Ramia Avatar asked Oct 02 '13 07:10

Aadith Ramia


1 Answers

First and foremost, as others have pointed out, you got to override GetHashCode as well. Something like:

public override int GetHashCode()
{
    return key.GetHashCode();
}
like image 171
nawfal Avatar answered Sep 28 '22 20:09

nawfal