Does OptionalFieldAttribute function really work?

In MSDN they write

Fields can be marked as optional using the optional FieldAttribute attribute. During deserialization, if there is no additional data, the serialization mechanism ignores the absence and does not throw an exception.

I cannot get an exception. I tried to create a class, tag it using SerializableAttribute, serialize the object using BinaryFormatter and transfer the state to a file on disk, and then add two fields to my class that I did not mark with the OptionalFieldAttribute parameter, and tried to deserialize the object back, which I only saved to disk. Am I surprised that an exception was not ruled out?

+6
source share
1 answer

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 required, you must set the AssemblyFormat property to BinaryFormatter

System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full

Default value

System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple

More information can be found here .

+7
source

Source: https://habr.com/ru/post/953005/


All Articles