views:

74

answers:

2

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?

+1  A: 

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.

John Saunders
+2  A: 

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.

  • I should qualify this: it only generates a serializer once and caches it for certain constructor overloads on the XmlSerializer. For others, it re-generates the serializer class every time you create an instance of the serializer.

As long as you use the vanilla constructor you are alright:

XmlSerializer ser = new XmlSerializer(typeof(MyType));
Rob Levine