XML Deserialization InvalidOperationException

Just a quick one today...

I was asked to help debug an issue with XMLSerialization in .Net where the object graph would serialize fine, but on being deserialized a InvalidOperationException was being thrown.

The class that caused the problem was defined in the following way:


public Class MyClass
{
public int MyInt { get; set; }
public DateTime MyDateTime { get; set; }

public MyClass(DateTime aDateTime)
{
MyDateTime = aDateTime;
}
}

This was nested inside another class in a collection, which initially I thought could be something to do with the problem. It turned out however that in order for deserialization from XML to work, each class that is to be deserialized must have a default constructor so that an instance of the class can be created by the XML deserializer.

This is easy to forget as the C# compiler implicitly adds a default constructor when there are no constructors in a class, but as soon as you add a non-default constructor, this goes away.

Simply adding


public MyClass(){}

Was enough to solve the problem.

The binary formatter does not suffer from this problem, although classes must be marked with the [Serializable] attribute.

Leave a Reply

Your email address will not be published. Required fields are marked *