The XmlSerializer has been in .Net since version 1.0 and has served us well for everything from Remoting, Web Services, serializing to a file, etc. However in .Net 3.0 the DataContractSerializer came along. And all of a sudden a lot of guidance suggests that we should use it over the old tried and true XmlSerializer. Wcf even uses this as the default mechanism for serialization. The question is, “Is it really better?”. The verdict is yes, and no. Like most things it depends on your implementation and what you need. For Wcf, you should prefer to use the DataContractSerializer. If you need full control over how the xml looks though, you should go back to the XmlSerializer.
What is Serialization?
Let’s start with the basics. Serialization has been a key part of .Net since version 1. It is basically the process of converting an object instance into a portable and transferable format. The objects can be serialized into all sorts of formats. 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 serializes. There are libraries out there to serialize to comma delimited strings, JSON, etc.
Deserialization is basically the reverse of serialization. Its the process of taking some data (Xml, binary, etc) and converting it back into an object.
1. 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 wan to serialize2. Full control over how a property is serialized including it it should be a node or an attribute3. Supports more of the XSD standard
2. Properties must be public
3. Properties must have a get and a set which can result in some awkward design
4. Supports a narrower set of types
5. Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too
1. Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize2. Because it is opt in you can serialize not only properties, but also fields. You can even serialize non-public members such as private or protected members. And you dont need a set on a property either (however without a setter you can serialize, but not deserialize)
3. Is about 10% faster than XmlSerializer to serialize the data because since you don’t have full control over how it is serialize, there is a lot that can be done to optimize the serialization/deserialization process.
4. Can understand the SerializableAttribute and know that it needs to be serialized
5. More options and control over KnownTypes