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]

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted @ Saturday, November 22, 2008 2:26 PM
Print

Comments on this entry:

No comments posted yet.

Your comment:



(not displayed)


 
 
 
 
 

Live Comment Preview:

 
«February»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910