Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the OptionalFieldAttribute actually work?

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?

like image 942
Mishax Avatar asked Sep 02 '13 19:09

Mishax


1 Answers

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.

like image 109
Mishax Avatar answered Oct 01 '22 19:10

Mishax