In C#, if I want to serialize an instance with XmlSerializer
, the object\'s type doesn\'t have to be marked with [Serializable]
attribute. However,
Right now there are really 3 forms of serialization in the .Net Framework.
There unfortunately is standard overall pattern for serialization. All 3 frameworks have different requirements and quirks.
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.
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.