From Framework Design Guidelines:
DO NOT implement value equality on mutable reference types. [p-270]
From Eric Evans's DDD:
Each ENTITY must have an operational way of establishing its identity with another object. [p-94]
Should I treat overriding Object.Equals method as identity operation or just compare the Identity attribute (e.g. customer1.Id == customer2.Id)?
There are three cases you might want to be able to distinguish.
You have two references to the same entity. In this case the normal equality operators will do their jobs correctly. No need to override anything.
You have two instances in memory of the same entity. When you design your repositories right this situation is avoidable but sometimes this is a situation you'll have to work with. Your customer1.Id == customer2.Id example will work fine in this case.
You have two different entities but you want to know if they have similar property value's. This might be a code-smell. You might be treating a value type as an entity. If this is really something you want to do then you should implement it separately from the normal .net == and .Equals mechanisms. (for example .IsSameAs(Customer subject)) to avoid confusion.
In case you consider overriding Object.Equals you have to keep in mind that you have also to override GetHashCode().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With