I serialize an XML file into an object using the built-in .NET functionality (XmlSerializer.Deserialize). After the object’s fields have been set, I want to act on that data by calling additional code in the object’s constructor. Unfortunately, stepping through the code reveals that the “additional” code is executed first before the serialization logic is executed. That makes the approach unfeasible, since there fields haven’t been initialized yet and there’s no data to act on.
Is there a known solution to this problem? Up to now, I’ve always called a second method that does this initialization of data, but it’s clunky and prone to errors: it has to be called after each serialization (other programmers might not be aware of that), or I have to create another wrapper to load the object (and stuff starts spiraling).
If a constructor is being invoked, it will always be the first thing (note that some serializers skip the constructor;
XmlSerializeralways runs a public parameterless constructor). As such, any logic will have to be in the properties etc.What you are really describing here is “serialization callback” – i.e. a way of getting the serializer to run a method of yours before and/or after serialization and/or deserialization; some serializers support callbacks – however,
XmlSerializerdoes not.The only option with
XmlSerializeris to implementIXmlSerializable, but frankly that is a huge pain. If possible, I would suggest either:DataContractSerializersupports callbacks and can do limited xml – not as fine-grained control asXmlSerializerthough (no attributes, in particular); protobuf-net supports callbacks if you want to switch to binary.