0

This is driving me crazy. I have a very simple question. When an object is being deserialized, will any constructor for that class be called? I am observing that none of my constructors are being called!!! I have searched on the net but I did not get any good explanations. Please enlighten me.

EDIT

Further to my bewilderment I have noted from net that there are two attributes available OnDeserializing and OnDeserialized. And now I see that they dont apply to constructors. I am confused.

EDIT2

Now what is this deserialization constructor that Marc is talking about here ?

Community
  • 1
  • 1
VivekDev
  • 20,868
  • 27
  • 132
  • 202
  • 1
    Deserialization using what? `BinaryFormatter`? `XmlSerializer`? ProtoBuf.net? – Lou Aug 04 '16 at 12:11
  • Its BinaryFormatter. But does that matter? – VivekDev Aug 04 '16 at 12:15
  • 1
    Only `BinaryFormatter` for classes implementing [`ISerializable`](https://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable(v=vs.110).aspx) expects the `protected ctor(SerializationInfo, StreamingContext)` (see [remarks](https://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable(v=vs.110).aspx#Anchor_2) in the MSDN article). If you use, say, `XmlSerializer`, it will require your class to have a public parameterless constructor (protobuf.net too, likely). Without posting some actual code, it's impossible to know what you are doing. – vgru Aug 04 '16 at 12:17
  • 1
    In any case, no serialization library will know which constructor to use and how to fill it, so there are two options: 1) a constructor with a specific argument list, or 2) plain parameterless constructor. – vgru Aug 04 '16 at 12:20
  • Ok, now I begin to understand. I have not implemented ISerializable. So now the final question(I hope). Does this mean that no constructor will be called in my case since i do not implement ISerializable? – VivekDev Aug 04 '16 at 12:23
  • 1
    [MSDN](https://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable(v=vs.110).aspx#Anchor_2): *Any class that might be serialized must be marked with the `[Serializable]` attribute. If a class **needs to control its serialization process**, it can implement the `ISerializable` interface*. So, if you just want `BinaryFormatter` to copy all your private fields, you don't need to do anything, and no constructor will be called. – vgru Aug 04 '16 at 12:27
  • Thanks Groo. Makes sense now. I was puzzled initially by the fact that an object can created without calling any constructor. – VivekDev Aug 04 '16 at 12:31

0 Answers0