Jonathan Allen
Jonathan Allen

Reputation: 70327

Why does the DataContractSerializer bypass initializers?

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

Upvotes: 3

Views: 357

Answers (1)

marc_s
marc_s

Reputation: 754973

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.

Upvotes: 3

Related Questions