On MSDN they write
Fields can be marked as optional by applying the OptionalFieldAttribute attribute to them. During deserialization, if the optional data is missing, the serialization engine ignores the absence and does not throw an exception.
I am unable to get an exception. I tried to create a class, mark it with the SerializableAttribute, serialize an object with BinaryFormatter and persist the state to a file on disk, and then add two fields to my class that I did not mark with the OptionalFieldAttribute, and tried to deserialize the object back that I just persisted to disk. I am surprised that no exception was thrown?
The MSDN page quoted does not mention this but the default behavior is that no exception will be thrown in this case. If an exception is desired you must set the AssemblyFormat
property of the BinaryFormatter
to
System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
The default value is
System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
More info can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With