How can I do versioning using Custom Serialization ?

Platform: WPF| Category: Serialization and Storage

Versioning can be done using serialization as follows.

[C#]
//Version 2.0.0.0
[Serializable]
public class MyClass : ISerializable
{
   public int Number;
   public int NewField;
   
   public void GetObjectData(
       SerializationInfo info,StreamingContext context)
   {
      info.AddValue('Number',Number);      
      info.AddValue('NewField',NewField);
   }

   protected MyClass(SerializationInfo info,StreamingContext context)
   {
      Number = info.GetInt32('Number');
      Version storedVersion = SerializationUtil.GetVersion(info);
      if(storedVersion.ToString() == '2.0.0.0')
      {
         NewField = info.GetInt32('NewField');
      }
      else
      {
         NewField = 123;//Some default value
      }
   }

   public MyClass()
   {}
}

public static class SerializationUtil
{
   static public Version GetVersion(SerializationInfo info)
   {
      string assemblyName = info.AssemblyName;
      /* AssemblyName is in the form of 'MyAssembly, Version=1.2.3.4,  
                              Culture=neutral,PublicKeyToken=null' */
      char[] separators = {’,’,’=’};
      string[] nameParts = assemblyName.Split(separators);
      return new Version(nameParts[2]);
   }
   //Rest of SerializationUtil
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.