views:

310

answers:

2

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)?

+4  A: 

There are three cases you might want to be able to distinguish.

  1. 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.

  2. 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.

  3. 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.

Mendelt
What do you mean by "when you design your repositories right"? How do you avoid the problem of more than one instance in memory?
dthrasher
You can have repositories keep a dictionary of references to loaded objects and their id's. Whenever an object is needed twice just return a reference to the same object. Most ORM's do this for you
Mendelt
A: 

In case you consider overriding Object.Equals you have to keep in mind that you have also to override GetHashCode().

Juri