This takes advantage of the fact that the binary serialization framework stores the type of each object, and so you don't have to know the type on deserialization.
Now, let MyData be the type we want to store:
- Do not mark MyData as [Serializable]. Instead,
- introduce the IMyDataStorage interface containing the single method ToMyData().
- Now, the first version of MyData's serialized format is introduced as the class (or struct) MyDataStorage1, implementing IMyDataStorage.
- Introduce the method IMyDataStorage MyData.ToMyDataStorage().
// Create an instance of the newest version of MyDataStorage.
IMyDataStorage storage = myData.ToMyDataStorage();
// Now, store it using regular binary serialization
using (Stream stream = new ...)
{
new BinaryFormatter.Serialize(stream, storage)
}
When deserializing, do this:
// Deserialize
IMyDataStorage storage = new BinaryFormatter.Deserialize(stream)
MyData myData = storage.ToMyData();
Now, when you need to change the serialized format, introduce MyDataStorage2, and upgrade the MyDataStorage1.ToMyData. Except for that, leave MyDataStorage1 unchanged.
When you decide an old format is obsolete, just delete your definition of the old serialized type (and handle the ensuing SerializationException!).