How do I write out an object that contains a reference to itself?

Using the default options with the standard serializer for data contracts gives you a configuration where object references are replaced by an actual instance of the object being referenced. In essence, the data contract serializer expands object references into copies of the original object. Implementing object references by making a copy solves one of the problems of contract-based data transfer- describing an object reference requires a description language that is a level abstracted from the user-controlled description of the data contents. After all, there are some pretty flexible description languages, like XML, that don't include object references in their minimal, core definitions.

Implementing object references by making a copy also creates a problem for data transfer- every time we want to insert a reference to an object, we have to make a whole new copy of that object. For some cases, that is simply wasteful. For other cases, such as circular object references, a copy-on-reference policy is entirely unworkable. The copy approach leads to an object graph of infinite size whereas the reference approach leads to an object graph of finite size. Clearly, that is a situation where we would prefer implementing object references with object references despite the other consequences.

WCF supports both copying and preserving object references. The default data contract serializer uses copies to implement object references. If you want to use object references to implement object references, then you can toggle the PreserveObjectReferences setting when creating the serializer to enable this behavior. Each serializer is free to solve this problem in its own way. For example, although DataContractSerializer defaults to copying references, the NetDataContractSerializer defaults to preserving references.

Next time: Replacing the Serializer