0

so I have read in the article that == check if the object reference is same or not .equals() check if data is the same or not but when I am writing some program on my own I am having confusion.

I have a class person I which I am passing 10,20 in my constructor now I have created another object p1 and p2

person p = new person(10,20);
person p1;
p1 = p;

person p2=new person(10,20);
Console.WriteLine(p==p1); //true
Console.WriteLine(p.Equals(p1)); //true
Console.WriteLine(object.ReferenceEquals(p,p1)); //true
Console.WriteLine(p == p2); //false
Console.WriteLine(p.Equals(p2)); //false confusion same data
Console.WriteLine(object.ReferenceEquals(p, p2));//false

now I have confusion in p.equals(p2) both have the same data 10,20 so why false

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Deepak Jain
  • 137
  • 1
  • 3
  • 27
  • 1
    Because you didn't implement; `Equals()` override, `==` override, nor implement the `IEquatable` interface, thus they are different objects so they cannot be equal. – Erik Philips Apr 27 '19 at 05:27
  • `==` checks if two instances are the same reference (which is, more or less are they pointing at the same object in memory). `Equals` checks the content. But for `Equals` to work on a self defined type, you have to override it. Otherwise it falls back to `Object.Equals` which of course does not know about the properties of the custom type. – derpirscher Apr 27 '19 at 05:30
  • if that case then why (p.Equals(p1)); is true ? @derpirscher – Deepak Jain Apr 27 '19 at 05:32
  • I don't know cthe exact implementation of `Object.Equals` but it may check for reference equality, which implies of course equality as well – derpirscher Apr 27 '19 at 05:35
  • @derpirscher You do not need to know the exact implementation, because that method Object.Equals is well documented. If it is an reference type then Equals is the same as ReferenceEquals – Sir Rufo Apr 27 '19 at 06:07

1 Answers1

0

p.Equals(p1) it will use Equals method of your object.

You did not implement it will compare address of two object, if it same address in memory it will true.

Note p1 = p that p1 and p refer to same address in memory.

person p2=new person(10,20) it will create object in difference address in memory with same content of p object

p.Equals(p2) has difference address in memory and no implement Equals method, it will return false.

You can implement Equals method like this

  public override bool Equals(Object obj)
       {
          person p= obj as person;
          if (p == null)
             return false;
          else
             return obj.p1 == p.p1 && obj.p2 = p.p2; // assum your property
       }

And you need implement GetHashCode method too like

public override int GetHashCode()
  {
    return this.p1 + this.p2; //sample
  }
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62