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?
In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.
In order to prevent subclass from serialization we need to implement writeObject() and readObject() methods which are executed by JVM during serialization and deserialization also NotSerializableException is made to be thrown from these methods.
Yes. If a parent implements Serializable then any child classes are also Serializable .
There are never any instances of static classes: they are both abstract and sealed in the IL, so the CLR will prevent any instances being created. Therefore there is nothing to serialize. Static fields are never serialized, and that's the only sort of state that a static class can have.
As a pragmatic workaround - don't mark the nesting type static
:
public class ContainerClass
{
private ContainerClass() { // hide the public ctor
throw new InvalidOperationException("no you don't");
}
public class SomeType
{
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With