-1

I have been trying to deserialize xml file while ago and had some problem that the serializer cannot find root element. Then I created constructor and everything works fine.

Can anyone explain me please why is this happening?

Thanks in advance.

  • Possible duplicate of [Why XML-Serializable class need a parameterless constructor](https://stackoverflow.com/questions/267724/why-xml-serializable-class-need-a-parameterless-constructor) – Fabjan Jan 25 '18 at 14:46

1 Answers1

1

The XmlSerializer will create instances of your types via reflection. To do so it must be able to instantiate your classes, which is by using its default-constructor. If you don´t have any, serializer can´t create the instance.

This is more or less the same thing, as serializer will do also:

Type type = // read type from XmlReader
var instance = Activator.CreateInstance(type);
property.SetProperty(instance, theValue);

Activator.CreateInstance however assumes a parameterless (=default) constructor. So if your class has another constructor defined, Activator can´t create the instance as it has no knowledge on the parameters to call the existing constructor, see here:

public class MyClass
{
    public string MyString { get; set; }
    public MyClass(string someString) { this.MyString = someString; }
}

Here Activator tries to create an instance of MyClass without any parameter, as it simply doesn´t know better. However MyClass excepts a string as parameter, making that call to fail.

If on the other hand MyClass has no constructor at all, the default-constructor is implicitely created for you. In this case you can savely create the instance via reflection.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111