Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the class constructor called while deserialising using XmlSerializer.Deserialize?

My application saves a class away using XmlSerializer, and then later when required, creates an instance by deserialising it again. I would like to use some property members of my class (assigned during deserialisation) in my constructor logic. It is ok to assume that the properties will be assigned first, and once all properties are assigned will the constructor be called?

Continuing on this topic, is there any documentation available on the sequence of events that take place during deserialisation?

like image 498
Satyajit Avatar asked Mar 04 '11 19:03

Satyajit


People also ask

Does Deserialization call constructor C#?

Constructors are not called when objects are deserialized. Therefore, any logic that executes during normal construction needs to be implemented as one of the serialization callbacks.

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.

How does the XmlSerializer work C#?

The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.

Why do we use XmlSerializer class?

XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.


1 Answers

No it is not OK to assume the properties will be set when the constructor runs. The opposite is true. The constructor is the very first piece of code which runs when an instance of an object is created. It's not possible for the properties to be set until after the constructor has started executing.

The XML deserialization process roughly looks like the following

  • Call the parameterless constructor
  • Set the properties to their deserialized values

A way to work around this is to use a factory method to do the deserialization and then run the logic which depends on the properties being set. For example

class MyClass {
  ...
  public static MyClass Deserialize(string xmlContents) {
    var local = ... // Do the XML deserialization
    local.PostCreateLogic();
    return local;
  }
}
like image 112
JaredPar Avatar answered Oct 02 '22 05:10

JaredPar