Wednesday, January 18, 2006

Serialization and type versions

After stating in my previous post that I write messages in en-GB, I go and ruin that by putting "Serialization" in the title of this one. Go figure.

Another nice addition in .NET 2.0 are five attributes in the System.Runtime.Serialization namespace. These help with telling v2 of a class how to cope when dealing with objects of type v1. The attributes are as follows:

OnDeserializedAttribute
OnDeserializingAttribute
OnSerializedAttribute
OnSerializingAttribute
OptionalFieldAttribute

Read the docs for usage, but essentially if you mark the new member fields in v2 with [OptionalField] then it doesn't fall over when attempting to deserialize an object of type v1, as it knows that the info might be missing. You can then use a method marked with [OnDeserialized] to do sensible things like set a default value for a missing field for example.

No comments: