What is the difference between obj1.Equals (obj2) and static Object.Equals (obj1, obj2) objects in C #?

from the Microsoft documentation, both Equals methods are essentially the same. But I just stumbled upon something very strange. in my Silverlight project, I have two instances of the same class that overrides Equals. If I ask inst1.Equals (inst2) or inst2.Equals (inst1), I will always return as a result. But Object.Equals (inst1, inst2) returns false. How is this possible?

Any ideas?

Thanks Roco

+3
source share
4 answers

obj1.Equals , obj1 null. object.Equals null. , ; , , .

+5

obj1.Equals , Object.Equals . Object.Equals - Equals, , . , .

+3

, Object.Equals , 2 , .

MyClass.Equals , 2 , , ( ).

+1

IEquatable<T>. :

public class SubjectDTO: IEquatable<SubjectDTO>
{
    public string Id;

    public bool Equals(SubjectDTO other)
    {
        return Object.Equals(Id, other.Id);
    }

    public override int GetHashCode()
    {
        return Id == null ? 1 : Id.GetHashCode();
    }
}

Looks fine, right? But when you try, you will find an amazing result:

var a = new SubjectDTO() { Id = "1"};
var b = new SubjectDTO() { Id = "1"};
Console.WriteLine(Object.Equals(a, b));
Console.WriteLine(a.Equals(b));

False
True

AND? Well, it’s important to overrideEquals(object other) :

public override bool Equals(object other)
{
    return other == null ? false : Equals(other as SubjectDTO);
}

When you add it to the class SubjectDTO, it will work as expected.

0
source

Source: https://habr.com/ru/post/1764525/


All Articles