Binary, SOAP and XML Serialization in C#

Serialization is the process of persisting the state of an object into stream of bytes. Its main purpose is to save the state of the object in a well-known format so that the object can be recreated at a later time. The process of recreating the object from a persisted stream of bytes is called Deserialization.

Below are some of the scenarios where Serialization/Deserialization process is used

  • Saving user preferences in the application.
  • Transferring objects across application domains.
  • Passing objects between heterogeneous systems.
  • Easily store application data into a stream of bytes.

There are different types of Serialization techniques available in .NET Framework. In this article we will briefly explain Binary Serialization, SOAP Serialization and XML Serialization techniques.

Any type decorated with Serializable attribute can participate in Serialization process. If you try to serialize an object that does not have Serializable attribute defined, SerializationException is thrown. If you determine that the Type has some member variables which does not need to be serialized, decorate these fields with NonSerializable attribute. It will reduce the size of the persisted data, also it will allow you to ignore the members which does not need to be recreated.

Serialize and Deserialize methods provided by the specific types are used to accomplish Serialization and Deserialization process.

Binary Serialization

In Binary Serialization, entire objects state (including private members) is persisted, fully quantified name of the types and also full name of the containing assembly is persisted. This type of serialization should be used when you want to transfer object across applications using same framework or when persisting objects for later use within the application.

System.Runtime.Serialization.Formatters.Binary namespace defines BinaryFormatter type used to serialize data in Binary compact form.

SOAP Serialization

In SOAP Serialization, the object state (including private members) is persisted in the form of a SOAP message, which is a standard to transfer objects to and from XML Web Services. This type of serialization is useful to transfer objects across heterogeneous systems.

System.Runtime.Serialization.Formatters.Soap namespace defines SoapFormatter type used to serialize objects into a SOAP compatible XML data.

XML Serialization

In XML Serialization, the object state (only public members) is persisted to a valid XML data. This type of serialization is useful to transfer objects across heterogeneous system and also to pass the data through firewalls. One important thing to remember is only public members are persisted in this type of Serialization.

System.Xml.Serialization namespace defines XmlSerilaizer type used to serialize objects into pure XML data.