I want to serialize a pretty ordinary class, but the catch is it's nested in a static class like this:
public static class StaticClass
{
[Serializable]
public class SomeType
{
...
}
}
This code:
StaticClass.SomeType obj = new StaticClass.SomeType();
XmlSerializer mySerializer = new XmlSerializer(typeof(obj));
Produces this error:
StaticClass.SomeType cannot be serialized. Static types cannot be used as parameters or return types.
That error seems completely irrelevant; StaticClass.SomeType
is not a static type.
Is there a way around this? Am I wrong to think this error is dumb?
Either make the class non nested or consider using the DataContractSerializer instead.
As a pragmatic workaround - don't mark the nesting type
static
:It's know limitation in XmlSerializer ()
And workaround is to use DataContractSerializer (DataContractAttribute + DataMemberAttribute)
As you can see DataContractSerializer doesn't even require
StaticClass
to be public. One difference is that you should useWriteObject' and
ReadObject' insteadSerialize
andDeserialize