The default comparison for equality in .Net, when comparing reference types, uses reference equality. The == operator compares the two class references and if they are the same instance (have a pointer to the same address in memory), returns true. Otherwise false.
In most of my day-to-day, however, I’d prefer to use value equality. That’s comparing the values of the properties of 2 instances of a class to determine equality.
Actually, I’d like to go one step further. I don’t want to compare all the properties of the class instances, just the ones that I determine indicate identity. So I whipped up a little interface IStructurallyIdentifiable<T> to help us out towards this goal. Implementers of this interface determine which properties determine identity for the class.
It is VERY important that the implementing class override Equals and GetHashCode. The compiler will force you to implement Equals<T>, and that will be enough for one-to-one comparisons, but if you want to use LINQ to Objects to handle equality comparisons of collections (think .Union, .Intersect, and .Except), you’ll need to override the implementations of .Equals and .GetHashCode. See the Phone class for an example.
One last note - if you’re looking for an implementation of the StaticReflection class, it’s in the following snippet, copied from Joel Abrahamsson’s blog.
Thanks for reading! If you have any suggestions for improvements, please add a comment or hit me up on Twitter!