How do I check if two Objects are equal in terms of their properties only without breaking the existing Object.Equals()?

If you have ReSharper installed (it's worth it!) then all you have to do is:

Alt+Insert

With your cursor inside the class. A partial class is good for hiding the boilerplate.

It'll automatically implement an equality check for each property.

(Select all properties w/ Ctrl+A, and you can check all w/ Space!)


Have you tried implementing your own IEqualityComparer? You can pass this to an .Equals() overload to define your own custom equality logic, as in

User A = User B even if they are distinct instances, if properties x, y, z are the same.

See this: MSDN

Edit: I should have written you can instantiate your EqualityComparer and pass two instances to its Equals() method and get a bool. Basic console app... will show true, false, false. Thing is trivial, has the two properties shown.

var comparer = new ThingEqualityComparer();

Console.WriteLine(comparer.Equals(new Thing() { Id = 1, Name = "1" }, new Thing() { Id = 1, Name = "1" }));
Console.WriteLine(comparer.Equals(new Thing() { Id = 1, Name = "1" }, new Thing() { Id = 2, Name = "2" }));
Console.WriteLine(comparer.Equals(new Thing() { Id = 1, Name = "1" }, null));


class ThingEqualityComparer : IEqualityComparer<Thing>
{
    public bool Equals(Thing x, Thing y)
    {
        if (x == null || y == null)
            return false;

        return (x.Id == y.Id && x.Name == y.Name);
    }

    public int GetHashCode(Thing obj)
    {
        return obj.GetHashCode();
    }
}

Too late to answer, but someone might end up here and I need to know my idea is right or wrong. If strictly values are the consideration, then why not make the objects JSON and compare the JSON strings? Like:

if (JsonConvert.SerializeObject(obj1) == JsonConvert.SerializeObject(obj2)) continue;