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?
First and foremost, as others have pointed out, you got to override GetHashCode
as well. Something like:
public override int GetHashCode()
{
return key.GetHashCode();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With