Is public declaration a requirement for a class to be serializable? I've been going through some code where all classes marked as [Serializable]
were also declared public. I could not find formal documentation stating this.
views:
68answers:
4No, there is no such requirement for Serializable
. It's not surprising that you see Serializable
on public classes, since data that's going to be persisted to a stream is very likely to be shared with others, and therefore motivates the choice of a public class.
I don't know .net very well. but what about private nested classes?
If the (public) outer class is serialisable then you'll probably want to serialise any inner classes as well.
Not always true, perhaps you have a object that has an internal class that represents the state of another object and is Serializable, that is quite valid too
Depends on the serialization. AFAIK, binary serialization (ie--[Serializable]) doesn't require public member access, it just does some voodoo to take an in-memory snapshot of the class.
XmlSerialization (and JsonSerialization, etc) do generally require the class be public, with a defualt parameterless constructor and automatically serialize all public properties or fields.