I\'m writing code to do Xml serialization. With below function.
public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSeria
This is a limitation of XmlSerializer
. Note that BinaryFormatter
and DataContractSerializer
do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.
Since you are using xml, you might consider using DataContractSerializer
and marking your class with [DataContract]
/[DataMember
], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute]
- everything becomes elements).
Update: if you really want to know, BinaryFormatter
et al use FormatterServices.GetUninitializedObject() to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:
Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.
I have my own serialization engine, but I don't intend making it use FormatterServices
; I quite like knowing that a constructor (any constructor) has actually executed.