Thursday, March 15, 2007

Version Tolerant Serialization in .NET

I recently wanted to revist the issue of serialization in .NET and the new features added in version 2.0 of .NET. (For those of you who have worked with earlier versions, you know the problems caused by added properties, changes in version numbers and the extra code needed to fix these issues). Here is a MSDN article that discusses the new features. In brief these new features are:

  • Tolerance of extraneous or unexpected data. This enables newer versions of the type to send data to older versions.
  • Tolerance of missing optional data. This enables older versions to send data to newer versions.
  • Serialization callbacks. This enables intelligent default value setting in cases where data is missing.
  • In addition, there is a feature for declaring when a new optional field has been added. This is the VersionAdded property of the OptionalFieldAttribute attribute.

MSDN link: http://msdn2.microsoft.com/en-us/library/ms229752.aspx

And the article summarizes with these best practices: To ensure proper versioning behavior, follow these rules when modifying a type from version to version:
  • Never remove a serialized field.
  • Never apply the NonSerializedAttribute attribute to a field if the attribute was not applied to the field in the previous version.
  • Never change the name or the type of a serialized field.
  • When adding a new serialized field, apply the OptionalFieldAttribute attribute.
  • When removing a NonSerializedAttribute attribute from a field (that was not serializable in a previous version), apply the OptionalFieldAttribute attribute.
  • For all optional fields, set meaningful defaults using the serialization callbacks unless 0 or null as defaults are acceptable.

To ensure that a type will be compatible with future serialization engines, follow these guidelines:

  • Always set the VersionAdded property on the OptionalFieldAttribute attribute correctly.
  • Avoid branched versioning.

No comments: