EqualityComparer <T>. Lack of misunderstanding?

I have a class Person, it implements the Equals () method from IEquatable<Person>(also overrides the method Object.Equals, now ignores the GetHashcode () method)

class Person : IEquatable<Person>
{
    public string Name { get; set; }

    public bool Equals(Person other)
    {
        return this.Name == other.Name;
    }
    public override bool Equals(object obj)
    {
        var person = obj as Person;
        return person != null && person.Name == Name;
    }
}

Ok, let's get started:

Person p1 = new Person() { Name = "a" };
Person p2 = new Person() { Name = "a" };

List<Person> lst1 = new List<Person>() { p1 };
List<Person> lst2 = new List<Person>() { p2 };

Let's talk about this line:

 bool b = lst1.SequenceEqual(lst2, EqualityComparer<Person>.Default);

I have a problem understanding this part:

EqualityComparer<Person>.Default

I heard that it EqualityComparer<Person>.Defaultchecks to see if the class implements IEquatable- it will take a method Equals(Person other), not Equals(object obj). he has the advantage of avoiding boxing

enter image description herebut

Equals(Person other)will run with or without output EqualityComparer<Person>.Default (because it implements IEquatable)

So what are we talking about boxing? not there!

The only time it Equals(object obj)will be launched will be:

bool b = lst1.SequenceEqual(lst2,EqualityComparer<Object>.Default);

! object, Person!

? EqualityComparer<Object>.Default. -, , , , ?

+5
3

null ( ), SequenceEquals EqualityComparer<T>.Default ( Enumerable ). , , EqualityComparer<T>.Default .

, , , EqualityComparer<T>.Default.

+1

, IEqualityComparer<object>.Default, , .NET 4.

, IEqualityComparer<BaseType> , IEqualityComparer<DerivedType>, DerivedType : BaseType. Person Object, , IEqualityComparer<Object> , IEqualityComparer<Person>.

+1

: http://msdn.microsoft.com/en-us/library/ms131187(v=vs.110).aspx

For a value type, you should always implement IEquatable and override Object.Equals (Object) to improve performance. Object.Equals indicates value types and relies on reflection to compare two values ​​for equality. Both your Equals implementation and your Object.Equals override should return consistent results.

Unless you override Equals and GetHashCode, EqualityComparer.Default will really take care of this for you.

0
source

All Articles