views:

68

answers:

4

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.

+3  A: 

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.

John Feminella
A: 

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.

Glen
A: 

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

almog.ori
A: 

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.

Wyatt Barnett