How to handle Binaryformatter Deserialize nulling/zeroing missing items?

For my game save/load I use the BinaryFormatter.Serialize() and Deserialize() to read/write a class containing my save data. All members of the class are initialised in the constructor to sensible initial values.

However, a problem occurs when adding new data like so:

  1. Add a new member to the save data class
  2. Run the game
  3. Save data is initialised, new item is initialised to a sensible value.
  4. Load previous save data with BinaryFormatter.Deserialize()
  5. New item is now null/zero

My question is simply how best to handle this case, as after the load, some items will need to be re-initialised and managing this over the course of many version of the save data may become a real pain.

Is there a way to deserialize without nulling missing items? Or a clever way to re-initialise anything that was nulled during the load?

Many thanks.

Implement the ISerializable interface, it allows you to write a custom serialization and deserialization procedure for a class. Also take a look at Data Contract Versioning.

I settled eventually on a solution which involves explicitly handling the data read/write using the ISerializable interface like this:

[System.Serializable]
public class MyData : ISerializable
{
   ....
   //data
   private int m_Currency		= 0;
   ....


    public void GetObjectData(SerializationInfo info, StreamingContext context)
	{
        ...
        info.AddValue("m_Currency",  m_Currency, m_Currency.GetType());
        ...
    }

    public MyData(SerializationInfo info, StreamingContext context)
    {
	   //init all data, as standard constructor is not called during deserialization
	   Init();

       foreach(SerializationEntry entry in info)
       {
		switch(entry.Name)
		{
        ...
		case "m_Currency": m_Currency = (int)entry.Value; break;
        ...

        }
      }
    }

   public MyData () 
   {
	   Init();
   }

   protected void Init()
   {
       m_Currency        = 0;
   }
}