Adam's blog formerly game development, now just casual madness

Serialization pitfall: Post-Deserialization

If you use .Net Serialization, especially Deserialization, you might want to have an object perform a specific action as soon as it has been deserialized, initialize some cache data, resolve references or something.

That’s why there is the OnDeserialized attribute (along with OnDeserializing, OnSerializing and OnSerialized). It just works in most cases – at least as long as you don’t expect any other object to be completely deserialized as well, not even “child objects”. OnDeserialized is just object-local behavior.

However, if you really need some post-deserialization step, there is the IDeserializationCallback interface, representing a single method that is invoked after the whole object tree has been deserialized. Great stuff. Just changed some lines and everything just works. Or does it? Not quite – because .Net classes rely on it as well, the Dictionary class for example, and you can’t safely expect your own callback to be called last. If you try to actually use a Dictionary during OnDeserialized or inside your callback, it will crash because of its comparer field being uninitialized i.e. null.

So if you really want your callback to be called after everything completely finished deserializing, you will need to do that manually. Nothing too bad, just something you need to know. Would’ve saved me an hour of trying to debug .Net Dictionary code, stepping through the BinaryFormatter file and double-checking custom SerializationTypeBinders.

54 of 74