Export (0) Print
Expand All

Interoperable Object References

By default the DataContractSerializer serializes objects by value. You can use the IsReference property to instruct the Data Contract Serializer to preserve object references when serializing objects of the type.

Generated XML

As an example, consider the following object:

[DataContract]
public class X
{
    SomeClass someInstance = new SomeClass();
    [DataMember]
    public SomeClass A = someInstance;
    [DataMember]
    public SomeClass B = someInstance;
}

public class SomeClass 
{
}

With PreserveObjectReferences set to false (the default), the following XML is generated:

<X>
   <A>contents of someInstance</A>
   <B>contents of someInstance</B>
</X>

With PreserveObjectReferences set to true, the following XML is generated:

<X>
   <A id="1">contents of someInstance</A>
   <B ref="1" />
</X>

However, XsdDataContractExporter does not describe the id and ref attributes in its schema, even when the preserveObjectReferences property is set to true.

Using IsReference

To generate object reference information that is valid according to the schema that describes it, apply the DataContractAttribute attribute to a type, and set the IsReference flag to true. Using IsReference in the previous example class X:

public class X

{

SomeClass someInstance = new SomeClass();

[DataMember(IsReference=true)]

public SomeClass A = someInstance;

[DataMember(IsReference=true)]

public SomeClass B = someInstance;

}

public class SomeClass

{

}

The generated XML is as follows:

<X>

<A id="1">

<Value>contents of A</Value>

</A>

<B ref="1">

</B>

</X>

Using IsReference ensures compliance on message round-tripping. Without it, when a type is generated from schema, what is sent back as XML for that type is not necessarily compatible with the schema originally assumed. In other words, although the id and ref attributes were serialized, the original schema could have barred these attributes (or all attributes) from occurring in the XML. With IsReference applied to a data member, the member continues to be recognized as "referenceable" when roundtripped.

See Also

Community Additions

ADD
Show:
© 2014 Microsoft