Not getting expected SerializationException when missing OptionalFieldAttribute

Discussion in 'Microsoft Dot NET Framework' started by Jeff Stewart, Aug 29, 2007.

  1. Jeff Stewart

    Jeff Stewart Guest

    I'm just discovered Version-Tolerant Serialization and am synthesizing
    it into an existing serialization scheme. What I read from the docs
    indicates that in the example below the .Deserialize() statement
    should throw a SerializationException indicating that field2 is
    expected from the data stream but Ver02.field2 is not marked with
    OptionalFieldAttribute. Yet I get no such exception when I munge the
    serialization of Ver01 a bit. Why?

    Jeff S.


    public class Ver01 : ISerializable {
    public string field1;

    public override GetObjectData(SerializationInfo info,
    StreamingContext context) {
    info.AssemblyName =
    typeof(Ver02).Assembly.FullName.Replace("", "");
    info.FullTypeName = typeof(Ver02).FullName;

    info.AddValue("field1", this.field1);

    public class Ver02 {
    public string field1;
    public string field2;

    public static class ExampleClass {
    public static void TryDeserialize() {
    MemoryStream memStream = new MemoryStream();

    // Create an old instance and serialize it to a memory stream.
    BinaryFormatter formatter = new BinaryFormatter();
    Ver01 oldVersion = new Ver01();
    oldVersion.field1 = "Hello world!";
    formatter.Serialize(memStream, oldVersion);

    // Reset stream for reading
    memStream.Position = 0;

    // Deserialize the old version into a new instance.
    Ver02 newVersion = (Ver02)formatter.Deserialize(memStream);
    Jeff Stewart, Aug 29, 2007
    1. Advertisements

  2. Jeff Stewart

    Jeff Stewart Guest

    Seems I found an answer:

    OptionalFieldAttribute isn't required in .NET 2.0 unless
    BinaryFormatter.AssemblyFormat == FormatterAssemblyStyle.Simple.
    Jeff Stewart, Aug 29, 2007
    1. Advertisements

  3. Jeff Stewart

    Jeff Stewart Guest

    Sorry, isn't required in .NET 2.0 *if* AssemblyFormat == Simple (the
    default in .NET 2.0).
    Jeff Stewart, Aug 29, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.