InvalidOperationException when serializing an object with an IXmlSerializable

I came across some interesting behavior with the XmlSerializer.

If I try to serialize a class that has an object property Type, and this object implements IXmlSerializable, the serializer will call InvalidOperationExceptionwith InnerException:

The type ConsoleApplication1.MyClass cannot be used in this context. To use ConsoleApplication1.MyClass as a parameter, a return type, or a member of a class or structure, the parameter, return type, or member must be declared as the type ConsoleApplication1.MyClass (it cannot be an object). Objects of type ConsoleApplication1.MyClass cannot be used in unsealed collections, such as ArrayLists.

However, if the object does NOT implement IXmlSerializable, the serializer will only execute the penalty.

Is this a bug in the way the XmlSerializer handles objects that are IXmlSerializable?

The following is a very simple case that might raise this exception.

public class SerializableClass
{
    public object Configuration { get; set; }
}

public class MyClass : IXmlSerializable
{
    public string MyProperty { get; set; }

    public MyClass()
    {
        MyProperty = string.Empty;
    }

    public System.Xml.Schema.XmlSchema GetSchema() { return null; }

    public void ReadXml(System.Xml.XmlReader reader) { /*Read*/ }

    public void WriteXml(System.Xml.XmlWriter writer) { /*Write*/ }
}

class Program
{
    static void Main(string[] args)
    {
        SerializableClass element = new SerializableClass
        {
            Configuration = new MyClass
            {
                MyProperty = "My Awesome Property"
            }
        };

        using (StringWriter writer = new StringWriter())
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableClass), new Type[] { typeof(MyClass) });
            serializer.Serialize(writer, element);
        }
    }
}
+4
source share
1 answer

The Configuration property in SerializableClass is causing problems. It is declared as an object, changing it to MyClass type will fix your problem.

public class SerializableClass
{
    public MyClass Configuration { get; set; }
}
0
source

Source: https://habr.com/ru/post/1539349/


All Articles