I have a simple class
[Serializable]
public class MyClass: ISerializable
{
public string var1;
public MyClass()
{
}
public MyClass(SerializationInfo info, StreamingContext context)
{
var1= info.GetString("var1");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("var1", var1);
}
}
which I serialized with
using(FileStream file = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(file, myClassInstance);
}
Than I decided to add a new field
[Serializable]
public class MyClass: ISerializable
{
public string var1;
[OptionalField]
public string var2;
public MyClass()
{
}
public MyClass(SerializationInfo info, StreamingContext context)
{
var1= info.GetString("var1");
var2= info.GetString("var2");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("var1", var1);
info.AddValue("var2", var2);
}
}
but I've got a serialization exception because the var2
field does not exists in the stream. Isn't the OptionalFieldAttribute
supposed to be especially made for that case ?! I have a workaround with a switch/case
but I dont understand why this does not work ?
[EDIT]
The bug was due to the fact that I used this dll in Matlab and all the assembly were not correctly loaded ! However, as mentionned by dbc
, the attribute is not taken into account when the ISerializable interface is implemented.