In my project I have a class which I Serialize in Binary format to the disk.
Due to some new requirement I need to create a new class which is derived from the original class.
eg
[Serializable]
public class Sample
{
String someString;
int someInt;
public Sample()
{
}
public Sample(String _someString, int _someInt)
{
this.someInt = _someInt;
this.someString = _someString;
}
public String SomeString
{
get { return someString; }
}
public int SomeInt
{
get { return someInt; }
}
}
[Serializable]
public class DerivedSample : Sample
{
String someMoreString;
int someMoreInt;
public DerivedSample ()
: base()
{
}
public DerivedSample (String _someString, int _someInt, String _someMoreString, int _someMoreInt)
:
base(_someString, _someInt)
{
this.someMoreString = _someMoreString;
this.someMoreInt = _someMoreInt;
}
public String SomeMoreString
{
get { return someMoreString; }
}
public int SomeMoreInt
{
get { return someMoreInt; }
}
}
When I try to De serialize an old file which contains only object of Sample it works fine, in the current assembly. That means backward compatibility is there. But when I try to deserialize the file which contains object of DerivedSample using the previous version of the assembly application crashes. Which means forward compatibilty needs to be taken care off…
It it possible to say read only the base class part of the object from new version of the file?
It seems from the question that what’s failing is the attempt to read a serialized DerivedSample into an application that has the old version of the assembly — thus there is no DerivedSample class, only the Sample class.
I don’t think this is intended to work, since the class that was serialized (DerivedSample) simply doesn’t exist in any form in the deserializing application.
Serialization seems to work best when the class itself is versioned rather than using inheritance. So you would modify Sample to add the new properties, rather than deriving from it. The new fields should be marked as optional (providing backward compatibility) and extraneous fields are ignored in deserialization into an older version (providing forward compatibility): http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx
Is that an option for you?