Note that there are some explanatory texts on larger screens.

plurals
  1. POObject Equality in .NET Domain Models
    primarykey
    data
    text
    <p>I'm looking for recommendations on best practices when implementing equality in a domain model. As I see it, there are three (3) types of equality:</p> <ol> <li><p>Referential Equality - meaning that both objects are stored in the same physical memory space.</p></li> <li><p>Identity Equality - meaning that both object have the same identity value. For instance, two Order objects with the same Order Number represent the same entity. This is especially important when storing values in lists, hashtables, etc. and the object needs a unique identity for lookup.</p></li> <li><p>Value Equality - both objects have all properties the same.</p></li> </ol> <p>By convention, .NET provides two (2) ways to test for equality: Equals and ==. So how do we map the three (3) types to the two (2) methods?</p> <p>I, of course, left out Object.ReferenceEquals which MS added in recognition that most people were overriding Equals because referential equality wasn't their desired behavior. So maybe we can cross off the first type (?).</p> <p>Given the behavior of GetHashCode and Equals in the context of a hashtable, is it safe to say that Equals should always provide Identity Equality? If so, how do we provide callers with as way to test for Value Equality?</p> <p>And, don't most developers assume that Equals and == will yield the same result? Since == tests referential equality, does this mean we should also be overloading == when we override Equals?</p> <p>Your thoughts?</p> <p><strong>UPDATE</strong></p> <p>I don't know all of the details but I was informed (in an in-person conversation with a colleague) that WPF has strict requirements that data-bound objects use referential equality for Equals or data-binding does not work correctly.</p> <p>Also, looking at typical Assert classes, there is even more confusing semantics. AreEqual(a, b) will typically use the Equals method implying Identity or Value Equality while AreSame(a, b) uses ReferenceEquals for Referential Equality.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload