views:

482

answers:

1

I just realized something crazy, which I assumed to be completely impossible : when deserializing an object, the DataContractSerializer doesn't call the constructor !

Take this class, for instance :

[DataContract]
public class Book
{
    public Book()
    { // breakpoint here
    }

    [DataMember(Order = 0)]
    public string Title { get; set; }
    [DataMember(Order = 1)]
    public string Author { get; set; }
    [DataMember(Order = 2)]
    public string Summary { get; set; }
}

When I deserialize an object of that class, the breakpoint is not hit. I have absolutely no idea how it is possible, since it is the only constructor for this object !

I assumed that perhaps an additional constructor was generated by the compiler because of the DataContract attribute, but I couldn't find it through reflection...

So, what I'd like to know is this : how could an instance of my class be created without the constructor being called ??

NOTE: I know that I can use the OnDeserializing attribute to initialize my object when deserialization begins, this is not the subject of my question.

+12  A: 

DataContractSerializer (like BinaryFormatter) doesn't use any constructor ;-p It creates the object as empty memory.

For example:

    Type type = typeof(Customer);
    object obj = System.Runtime.Serialization.
        FormatterServices.GetUninitializedObject(type);

The assumption is that the deserialization process (or callbacks if necessary) will fully initialize it.

Marc Gravell
+1 - YUP, mind-boggling at first, but that's the way it is!
marc_s
This is not entirely true (or could be understood wrong): the DataContractSerializer will create a chunk of memory big enough to hold the object, and then it will fill in those fields it knows about from the stream it's deserializing from - so after deserialization, you do have a valid object with the values filled in from the stream it's been deserialized from (it's not all empty after deserialization)
marc_s
Thanks Marc ! I was completely unaware of that GetUninitializedObject method...
Thomas Levesque
Learn something new every day.. I'm relatively new to WCF and I ran into this today as well. Made me go "WTF?" for a moment :)
Thorarin
This is CHEATING !!
Cheeso
Yup. But it is what happens...
Marc Gravell
Interesting - I completely missed this point when skimming the MSDN docs on DataSerializer, and ended up at this post from googling - d'oh!
snemarch