0

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.

GuillaumeA
  • 3,493
  • 4
  • 35
  • 69
  • possible duplicate of http://stackoverflow.com/questions/929985/whats-up-with-the-optionalfield-attribute – 1.618 Oct 13 '15 at 20:36
  • look on it too: http://stackoverflow.com/questions/5381928/deserialization-backwards-compatibility – Ilya Chumakov Oct 13 '15 at 20:42
  • Once you mark the class as `ISerializable`, then `[OptionalField]` doesn't matter because you're doing everything manually. To avoid the exception, see [Is ISerializable backwards-compatible with previous versions of classes with fewer fields?](https://stackoverflow.com/questions/32640774) or [Changing types during binary deserialization in C#](https://stackoverflow.com/questions/30021070/). – dbc Oct 13 '15 at 22:48

0 Answers0