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

1
  • @VladL Thanks, I did not see this question Commented Mar 10, 2013 at 13:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.