14

If i have a complex object, what is the best practice pattern to write code to compare 2 instances to see if they are the same

leora
  • 188,729
  • 360
  • 878
  • 1,366

3 Answers3

18

Implement the IEquatable interface. This defines a generalized method that a value type or class implements to create a type-specific method for determining equality of instances. Don't forget to override Equals(object) as well. More information here:

http://msdn.microsoft.com/en-us/library/ms131187.aspx

Ray Booysen
  • 28,894
  • 13
  • 84
  • 111
2

I think the answer is highly problem dependent. For example, you may want to consider objects equal only if all of their properties are equivalent. This would perhaps be the case where each object doesn't have a uniquely identifying property. If there is such a property (or properties), say an ID or ID and Version, that uniquely identifies each object of the type, then you may only want to compare based on that property (or properties).

The base pattern, however, ought to be something like:

if their references are equal (includes both null)
   return true
else if one object is null
   return false
else
   return value based on relevant properties

Note that if you override the Equals operator, you'll also want to override GetHashCode() so that the hash codes for equivalent objects are the same. This will ensure that data structures that use the hash code for determining duplicate keys work properly when the object is used as a key.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

Since you mentioned a Complex Object, make sure that all composite Objects in the Complex Object implement equals(Object) as mentioned by tvanfosson. Finally implement equals in the Complex object taking advantage of the equals of all composite Objects

Sathish
  • 20,660
  • 24
  • 63
  • 71