I have an existing code base that saves a couple of simple classes to disk through the NetDataContractSerializer , but the classes are unfortunately not decorated with [DataContract] , but rather [Serializable] . This works fine, but now I want to add a few new properties to the saved classes, while retaining the ability to read files created by the old version.
Let's say this is a class:
[Serializable] public class Persisted { public int OldProperty {get;set;} public int NewProperty {get;set;} }
Now, when I deserialize old files, I get an exception because they do not contain NewProperty . It makes sense. Therefore, I would like to ignore NewProperty , but if the [OptionalField] attribute is present, so that the serializer ignores the missing field, it cannot be applied to property fields - only.
So, I decided that I would use [DataContract] and [DataMember] , which also has the IsRequired property, but this changes the layout of the serialized file and cannot read old data files. In addition, you cannot mix [Serializable] and [DataMember] - if the serializer sees the [Serializable] attribute, it ignores the [DataMember] directives.
Thus, banning the ability to convert old files once (maybe, but not my first choice), is there a way to force NetDataContractSerializer to ignore a field in an existing XML serialized object?
Avner shahar-kashtan
source share