I have a class, that should support version tolerant serialization
[Serializable]
class A {
[OptionalField]
int a;
[OptionalField]
MyClass b;
[OptionalField]
MyClass c;
}
- How can I correct missing fields after deserialization? I guess, I have to use method marked with
[OnDeserializing]. But how can I get which of fields was ignored? - Can I configure auto-deserialization to initialize field by default constructor in case of them missing?
Additionally, you can use OnSerializingAttribute and OnSerializedAttribute to set the fields. As the example shows, fields that have been already set will keep their value. Note, however, that this is only the case if the field is set during the OnSerializing event. Fields set during the OnSerialized event will override the serialized value.
EDIT: In this case you can check in your method (decorated with OnSerialized) if the field equals to null and instantiate when necessary. If there is the possibility that this field is never be used and its creation can be deferred, think about hiding the field in question behind a property and instantiate it lazily.
Models.cs:
Program.cs:
Output: