Freigeben über


DataMember Best Practices

I was asked to share a list of best practices I wrote for data contracts and data members so here it is:

1.
Do apply the DataMember attribute only to properties rather than the corresponding fields.
2.
Do not use type inheritance to version a data contract. Either modify the existing type or create an entirely new type.
3.
Do not add or remove enumeration members between versions.
4.
Do not change the name or namespace of a data contract or data members between versions.
5.
Do not change the order of data members between versions.
6.
Do set the IsRequired property to false on data members added in later versions.
7.
Do not remove data members in later versions even if they are marked as not required.
8.
Do support IExtensibleDataObject on data contracts to support future compatibility with extended types.
9.
Do apply the DataMember attribute only to public members. Serialization of private data members is not supported for partial trust environments.
10.
Do not rely on constructor visibility, constructor link demands, constructor security actions, or validation checks in the constructor to make a DataContract type safe for partially trusted callers. DataContractSerializer does not invoke the constructor when initializing an object.

Next time: Using Call Context Initializers for Cleanup

Comments

  • Anonymous
    February 22, 2008
    What are the consequences of adding enum members to a DataContract between versions? What bad things result from reordering data members?

  • Anonymous
    February 22, 2008
    How can I directly craft the XML content that goes into a fault detail? Getting control over the detail

  • Anonymous
    February 24, 2008
    Hi Jeff, Adding or removing enum members is a breaking change because unlike adding or removing data members, there's no concept of a default value or extensibility hook to handle unknown enum values. Reordering data members breaks parsers that assume a particular sequence of elements in a complex type.  In most cases it's relatively easy to avoid this even when changing a contract by explicitly setting the Order on the attribute.