EqualityComparer <T> .Default does not return the received EqualityComparer
I have a Person class and an created equality comperer class derived from EqualityComparer <Man>. However by default EqualityComparer does not call the Equals function of my comparison equals
According to MSDN EqualityComparer <T> .Default :
The Default property checks whether the type T implements the System.IEquatable interface, and if so, returns the EqualityComparer that uses this implementation. Otherwise, it returns EqualityComparer, which uses the Object.Equals and Object.GetHashCode overrides provided by T.
In the example (simplified) below, the Person class does not implement the implementation of System.IEquatable <Man>. Therefore, I expect PersonComparer.Default to return an instance of PersonComparer.
However, PersonComparer.Equals is not called. There is no debug output, and the return value is false.
public class Person
{
public string Name { get; set; }
}
public class PersonComparer : EqualityComparer<Person>
{
public override bool Equals(Person x, Person y)
{
Debug.WriteLine("PersonComparer.Equals called");
return true;
}
public override int GetHashCode(Person obj)
{
Debug.WriteLine("PersonComparer.GetHasCode called");
return obj.Name.GetHashCode();
}
}
public static void Main()
{
Person x = new Person() { Name = "x" };
Person y = new Person() { Name = "x" };
bool b1 = PersonComparer.Default.Equals(x, y);
}
Question: What am I doing wrong?
If you are wondering why I do not want to implement IEquatable <Person>.
My problem is comparable to string comparison. Sometimes you want two lines to be equal if they were exactly the same lines, sometimes you want to ignore the case, and sometimes you want to treat characters like etc., as if they were an o character.
: Person -, , MemoryStream. , , , . .
unit Test: - , , . , , Person ( , EF 6). IEquatable, false, . , , , Person. , O o -
This is because the property Default EqualityComparer<T>does not return a PersonComparer, but a ObjectEqualityComparer<T>. And that ObjectEqualityComparer<T>when you referenced the documentation is compared using Equalson Person.
See the actual source . On line 89, it returns ObjectEqualityComparer<T>.
There is nothing wrong with your code, as you can see when you are actually trying to run your code on an instance PersonComparer:
bool b1 = new PersonComparer().Equals(x, y);