Introduction to Serialization

Introduction

Serialization is a way changing objects into a compatible format to stream across process boundaries and machines. This type of data makes it easy to transmit over a network or into a persistent storage location, like a file, database, or ASP.NET cache. The serialized data can be read by both sending and receiving machines or processes, and creates a strong form of communication that is cross-platform-compatible. Once the stream has reached the other process, it is deserialized and the same object is reconstructed to its original format.

In .NET, serialization can be done by .NET Remoting, implementing web services or WCF services to transmit data between a server and a client.

Serialization is provided by the System.Runtime.Serialization namespace and its Iformatter interface. IFormatter contains the methods called Serialize and De-serialize that save and load data to and from a stream. Essentially, all that is needed is a stream and a formatter, where the stream acts as a container for the serialized object, and the formatter is used to serialize these objects onto the stream.

Besides passing objects from one application or domain to another, some practical advantages of serialization are being able to modify XML documents without using the Document Object Model (DOM), and these XML files can pass through a firewall.

Some disadvantages however is the CPU and IO resource consumption involved with serializing and deserializing objects. Serialization is slow and the latency when transmitting the data over the network should be taken to the consideration. As well, XML serialization is insecure as it works on public members and public classes. Private or internal classes are not supported, allowing the class to be accessed by anyone.

To serialize a class, the Serializable attribute must be declared, and all of its members become serializable, except if they contain the NonSerialized attribute attribute which just ignores them. Private and public members of a class are always serialized by default, and the Serialization attribute is only used for the binary serialization.

An example of a simple class might be:
[Serializable]
public class Book
{

public string Author;
public string Title;

}
The Serializable attribute is specified at the beginning of the class, in square brackets above the class declaration. Even if the ISerializable interface has not been implemented inside the class, it is a good practice to apply the Serializable attribute.

If this attribute was not declared in the beginning of the class, then when we try to serialize an object the CLR throws a SerializationException.

Copyright © All Rights Reserved - C# Learners