Serialization and versionning
-
I'm developping an application where I need to serialize objects. But the properties of these objects may change during the developpment as I could add new options. For instance, I may have this class Car { // version1 string ModelName; int Speed_Mph; } And then I want to serialize an array of Car into a binary file (foo.sav) Later, I add the color : class Car { // version1 string ModelName; int Speed_Mph; // version 1.1 string Color; } Now, if I try to used the deserialization function with foo.sav, it won't work, because foo.sav didn't contain the Color properties for Car. What is the easiest / msot efficient way to solve it? I have several ideas in mind, but I don't know the better ones. The most efficient one seems to be to write my own ISerializable interface, and start by reading the version. It works, but I'm afraid it's a lot of work, as I need to assign the keys one by one, needn't I?
-
I'm developping an application where I need to serialize objects. But the properties of these objects may change during the developpment as I could add new options. For instance, I may have this class Car { // version1 string ModelName; int Speed_Mph; } And then I want to serialize an array of Car into a binary file (foo.sav) Later, I add the color : class Car { // version1 string ModelName; int Speed_Mph; // version 1.1 string Color; } Now, if I try to used the deserialization function with foo.sav, it won't work, because foo.sav didn't contain the Color properties for Car. What is the easiest / msot efficient way to solve it? I have several ideas in mind, but I don't know the better ones. The most efficient one seems to be to write my own ISerializable interface, and start by reading the version. It works, but I'm afraid it's a lot of work, as I need to assign the keys one by one, needn't I?
One way would be to implement the
ISerializable
interface and take these things into account yourself. Another way - especially if your assemblies are versioned (or better yet, strongly named) - is to extend theSerializationBinder
and overrideBindToType
so that when an older Type (since a Type name includes not only the fully-qualified class name but also the assembly information) you bind it to your new Type. You'd still have to take into account any changes, but this is a common and pretty efficient way of solving the problem of versioning. See the documentation for theSerializationBinder
method in the .NET Framework SDK for more information and an example.Microsoft MVP, Visual C# My Articles