.NET 2.0 introduced Version Tolerant Serialisation. This allows a Serializable
class to have fields marked with an OptionalFieldAttribute
. This means you can change the class by adding optional fields (or removing optional fields) and still deserialise data from the previous class versions.
I have a Data Transfer Object class that is only used to pass query criteria to a data access class. The idea is that by serialising the object we can let users can save their queries, but I was worried that changes to the class would render previously saved queries unusable. As every field is nullable (users only define a subset of the available criteria) I have been able to mark them all as optional. This means we can add and remove fields and still recreate the object from a previously serialised version. Fields dropped from the previous version will be ignored (they presumably no longer have meaning if they are dropped), and newly-added fields will get their default value.
There is at least one situation it won’t handle: changing the type of a field will break the deserialisation. We’ll just have to catch that and let the user know their query no longer works, possibly while begging forgiveness :-).