1

I wonder why a class can not do serialization without empty constructor.

I tried it a few times when I got this error message:

ClassName cannot be serialized because it does not have a parameterless constructor.

The code goes like this:

   public void DoSerialize(string path)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));
            TextWriter textWriter = new StreamWriter(path);
            serializer.Serialize(textWriter, MyList);
            textWriter.Close();
        }
        catch (Exception e)
        {

        }
    }

Really, when I added an empty constructor it worked

Hodaya Shalom
  • 4,327
  • 12
  • 57
  • 111

1 Answers1

5

On deserialization XmlSerializer needs to create an object of your class, and then set its attributes one-by-one from the XML. In order to do so, the serializer must construct the object, and it uses the default parameterless constructor for that. It cannot use other constructors, because it does not know what attributes it needs to pass to them.

An inability to create instances of objects lacking parameterless constructors has been recognized as a problem, and fixed in the later versions of .NET by providing a backdoor way of creating uninitialized objects with FormatterServices.GetUninitializedObject. However, XMLSerializer has been left in its current state.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523