views:

18

answers:

1

Why does the DataContractSerializer bypass initializers?

Background:

The serialization formatter gets uninitialized instances of classes during deserialization. That is, instances where all fields are set to their default values. For reference types this will be null. That is why "authors" in this case causes a null reference exception. You have to create it in the property like the code you have commented out. By including this "lazy" initialization code for authors you can remove the field initializer. Also, you must change the constructor to use the Property and not the field direclty.

/Calle http://social.msdn.microsoft.com/Forums/en-CA/netfxremoting/thread/b786050e-4850-4739-8b2e-d57e35d95952

+3  A: 

For performance reasons - it seems deserializing using the default parameterless constructor and setting the properties is fairly slow - the way WCF handles it is much faster.

For that reason, the DataContractSerializer doesn't require a parameterless, public constructor (like the XmlSerializer does) - you don't need that, it won't be used anyway.

marc_s
Well I certainly do like dropping the parameterless, public constructor requirement.
Jonathan Allen