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?
Share
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: