confusion for .equals() and == C#?

117 Views Asked by At

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

1

There are 1 best solutions below

4
On

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
  }