Version Tolerant Serialization

At times you may need to update your objects and add additional properties, and maybe you still have old clients that consume your objects, so you will need to update your objects in a way that makes it backwards compatible. That's where Version Tolerant Serialization comes in.

Let's say you have an object with one property. You add a second property called "MyProperty2", and the change needs to be version tolerant. You can implement ISerializable and do this:
public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        SerializationInfoEnumerator serializationInfoEnumerator = info.GetEnumerator();

        while (serializationInfoEnumerator.MoveNext())
        {
            switch (serializationInfoEnumerator.Name)
            {
                case "MyProperty":
                    MyProperty = info.GetString("MyProperty");
                    break;
                case "MyProperty2":
                    MyProperty2 = info.GetString("MyProperty2");
                    break;
                default:
                    break;
            }
        }
    }
You can also implement IDeserializationCallback to default your new property.

Of course if you are using .NET 2.0 or above, you should use the OptionalField attribute to mark your new property as optional.

    [OptionalField]
    private string myVar2;

And you can use these attributes to control your serialization:

    [OnDeserialized]
    [OnDeserializing]
    [OnSerialized]
    [OnSerializing]

posted @ Saturday, November 22, 2008 2:26 PM
Print

Comments on this entry:

No comments posted yet.

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«June»
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456