Reputation: 59476
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.
Upvotes: 0
Views: 147
Reputation: 311605
No, 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.
Upvotes: 3
Reputation: 15663
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.
Upvotes: 0
Reputation: 7889
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
Upvotes: 0
Reputation: 22300
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.
Upvotes: 0