Reputation: 11403
It's totally well known that in order to be able to serialize your objects using XmlSerializer you have to declare their classes as public -otherwise you get an InvalidOperationException. The question here is why? I Googled and I found out that XmlSerializer actually generates and compiles a brand new assembly and then uses this assembly to serialize your objects. The question is, still, why does it require the class to be public, while it's easy to get access to internal types in my assembly using reflection?
Upvotes: 0
Views: 315
Reputation: 41308
Quite simply because it doesn't use reflection in order to serialise/deserialise your class - it access the public properties (and classes) directly.
Using refleciton to access members would be extremely expensive so instead, as you mention in your question, it generates a serializer class once using reflection, caches it*, and from this point onwards uses direct member access.
As long as you use the vanilla constructor you are alright:
XmlSerializer ser = new XmlSerializer(typeof(MyType));
Upvotes: 2
Reputation: 161783
The simple reason is because it's been that way since Day 1.
Also, Reflection is expensive. Why do it if you don't have to?
Also, the XML Serializer isn't intended to serialize every class in the world. It's meant to serialize classes designed to be serialized. As such, it's no great burden to make sure the data you want is in public fields and properties of a public class with a public parameterless constructor.
It's only when you try to serialize a type that was not designed to be serialized that you run into trouble.
Upvotes: 1