XmlSerializer Problems

Just stumbled onto an exotic bug in the framework:

using System;
using System.Xml.Serialization;
using System.IO;
namespace Repro
{
class Program
{
static void Main(string[] args)
{
new XmlSerializer(typeof(StaticClass.NestedClass));
}
}
public static class StaticClass
{
[Serializable]
public class NestedClass
{
}
}
}

Even though there will never be a need to instantiate StaticClass, this will fail with an InvalidOperationException stating that “Repro.StaticClass cannot be serialized. Static types cannot be used as parameters or return types.”

Weird.

[Update: There’s another one! The reason I moved to XmlSerializer instead of SoapFormatter was because SoapFormatter doesn’t support generics and now:

namespace Repro
{
class Program
{
static void Main(string[] args)
{
new XmlSerializer(typeof(C));
}
}
[Serializable]
public class A
{
}
[Serializable]
public class B<T> : A, IEnumerable<T>
{
// ...
}
public class C : B<int>
{
public void Add(int value)
{
// ...
}
}
}

The above code throws another InvalidOperationException, stating that ‘To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy.’ Moving the Add method to B works and I could understand it if I actually wanted to serialize an object of type B, but come on!

I’ve tried re-implementing IEnumerable<T> in C, but that doesn’t work either.

This is quickly becoming very frustrating.]

Advertisements

One thought on “XmlSerializer Problems

  1. “… cannot be serialized. Static types cannot be used as parameters or return types.”
    Weird indeed.
    Thanks for the post — it helped me to figure out and fix the problem.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s