XmlSerializer will use the Equals() method to find circular references

This post saved me quite a bit of time:

http://sqljunkies.com/WebLog/kmarple/archive/2005/01/11/6180.aspx

 We were having a problem with serializing a domain object.  It was reporting a circular reference problem.  We found out that because we had overriden the Equals method to compare our ids, the XmlSerializer thought all the objects were the same if the id had not been assigned yet.  Assigning an id up front solved this serialization issue.
 

2 comments

  1. jeremiah johnson

    only override equals if you need to. the default equals implementation will return true if two objects are the same, and you should ALWAYS override GetHashCode() if you override Equals().

    Why? Because GetHashCode() is a way of uniquely identifying your object. By default, it returns a representation of the memory location of that object. If you override Equals() without overriding GetHashCode() you *will* have problems. Objects that are considered equal to one another via the Equals() method MUST return the same int from GetHashCode() or things will break.

    If you want to determine if two objects are the same actual object living at the exact same point in memory (i.e. they are two references to the same object), leave Equals() and GetHashCode() alone.

    If you want to be able to determine if the contents of two of your objects are identical, override Equals() AND GetHashCode(). There is no need to add an id field simply to determine equality.

    Read more here (this is a Java example, but it is valid in C# also)
    http://www.vipan.com/htdocs/hashcode_help.html

  2. Jeremiah,
    Great comment. You are right: only override equals if you need to. If you do, be sure to override GetHashCode() as well.

Comments are closed.