0

I really need to compare two objects with the same class, I have one grid with one list and need to check which one is the user changes. Here is the example

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

I tried to use

Person p1 = new Person { Name = "Jay", Age = 25 };
Person p2 = p1;
Person p3 = new Person { Name = "Jay", Age = 25 };

Console.WriteLine(p1.Equals(p2));  // True
Console.WriteLine(p1 == p2);       // True

Console.WriteLine(p1.Equals(p3));  // False
Console.WriteLine(p1 == p3);       // False

In resume, I don't know to compare properly two objects, use == or .equals, please note that object two are copy of object one at the begin of process.

VhsPiceros
  • 410
  • 1
  • 8
  • 17
  • 6
    Look at overriding Equals and GetHashCode – Matthew Apr 14 '19 at 15:12
  • 1
    `p1` and `p3` have only the same values of properties... but they are different objects. As @Matthew said - try to override `Equals` and `GetHashCode` methods (there you can implement how you would like to compare objects in order to say "objects are equal") – demo Apr 14 '19 at 15:19
  • 4
    Your user example may be a simplification, but in general one should be very careful with defining equality for class types. There are people with my name and age that aren’t *me*. I usually advise against overriding Equals/GetHashCode and instead implement specific comparers like `class SameNameAndAgeComparer : IEqualityComparer` and compare using that. – Anders Forsgren Apr 14 '19 at 15:25

1 Answers1

2

The difference between == operator and Equals resides in the fact that == operator is used to compare the references contrary to Equals which is used to compare contents .

Best regards .

sayah imad
  • 1,507
  • 3
  • 16
  • 24