Why doesn't the XmlSerializer need the type to be marked [Serializable]?

This is because XmlSerializer only serializes public fields/properties. Other forms of serialization can serialize private data, which constitutes a potential security risk, so you have to "opt in" using an attribute.


Security isn't the only issue; simply, serialization only makes sense for certain classes. For example, it makes little snse to serialize a "connection". A connection string, sure, but the connection itself? nah. Likewise, anything that requires an unmanaged pointer/handle is not going to serialize very well. Nor are delegates.

Additionally, XmlSerializer and DataContractSerializer (by default) are tree serializers, not graph serializers - so any recursive links (like Parent) will cause it to break.

Marking the class with the serializer's preferred token is simply a way of saying "and it should make sense".

IIRC, both [XmlSerializer and [DataContractSerializer] used to be very rigid about demanding things like [Serializable], [DataContract] or [IXmlSerializable], but they have become a bit more liberal lately.


Right now there are really 3 forms of serialization in the .Net Framework.

  1. XmlSerialization - By default works on public fields and properties. Can still be controlled via XmlElementAttribute, XmlAttributeAttribute, etc ...
  2. BinarySerialization - Controlled by the SerializationAttribute. Deeply integrated into the CLR
  3. WCF Seralization - DataContractAttribute, etc ...

There unfortunately is standard overall pattern for serialization. All 3 frameworks have different requirements and quirks.