Thursday, November 25, 2010

Difference between XmlSerializer and DataContractSerializer (WCF)

Lets start with, what is serialization?
It is the process of converting an object instance into a format that can be persisted and formated. The objects can be serialized into all sorts of formats(Xml, binary, json, etc). Serializing to Xml is most often used for its interoperability. Serializing to binary is useful when you want to send the object from one .Net application to another. .Net even supports the interfaces and base classes to build your own serialization format.

Deserialization is basically the reverse of serialization. Its the process of taking some data (Xml, binary, json, etc) and converting it back into an object.

I want to point out, that the differences between XmlSerializer and DataContractSerializer are in context of WCF.
  • Opt-out rather than opt-in properties to serialize. This mean you don’t have to specify each and every property to serialize, only those you don’t want to serialize
  • Full control over how a property is serialized including it being a node or an attribute
  • Supports more of the XSD standard
  • Can only serialize properties
  • Properties must be public
  • Properties must have a get and a set which can result in some awkward design
  • Supports a narrower set of types
  • Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too
  • Opt-in rather than opt-out properties to serialize. This means, you specify what you want to serialize
  • Because it is opt in model, you can serialize not only properties, but also fields. You can even serialize non-public members. And you don't need a set on a property either (however without a setter you can serialize, but not deserialize)
  • Is faster than XmlSerializer because you don’t have full control over how it is serialized, there is a lot that can be done to optimize the serialization/deserialization process.
  • Can understand the SerializableAttribute and know that it needs to be serialized
  • More options and control over KnownTypes
  • No control over how the object is serialized outside of setting the name and the order

For WCF, prefer to use the DataContractSerializer. But if you need full control over how the xml looks, use XmlSerializer.