joydip_kanjilal
Contributor

How to work with serialization in .Net

opinion
Feb 12, 20164 mins
Software Development

Serialization converts an object's state into a stream of bytes so that it can be persisted in a permanent or temporary storage medium

When working with applications, you’ll often need to store data in a persistent or non-persistent storage medium so that the same data can be retrieved at a later point of time. Serialization, a feature provided by the CLR, can help you to achieve this.

Serialization may be defined as the process of converting an object into a stream of bytes, persisting the object’s state into the memory, database of a file. The reverse of serialization is deserialization, which reconstructs the object from the stream of bytes. In other words, deserialization is the process of converting a serialized object into its original state.

Serialization is necessary to pass an object over the wire — it facilitates the transmission of an object over a network. Therefore, you can leverage serialization to pass an object from one application domain to another. You can also take advantage of serialization to create a clone of an object.

However, serialization is also costly because of the resource overhead involved in serializing and de-serializing objects. To work with Serialization in .Net you should take advantage of the System.Runtime.Serialization namespace, i.e., you should include this namespace in your program.

You can make a class serializable using the [Serializable] attribute. Here’s an example that shows how you can apply this attribute on a class.

[Serializable]

public class Product

{

   public int productCode;

   public string productName;

}

Now, if you would like to restrict one or more members of a class from being serialized, you can use the NonSerialized attribute as shown in the code snippet given below.

[Serializable]

    public class Product

    {

        public int productCode;

        public string productName;

        [NonSerialized()]

        public double productPrice;

    }

The .Net framework provides support for the following types of serialization.

  1. Binary
  2. SOAP
  3. XML
  4. Custom

Binary serialization

Binary serialization is the fastest of all the serialization techniques — it can be used to serialize an object to a binary stream. It is a type of serialization that can be used to serialize an object to an output stream while preserving the object’s identity — the type information is not lost in the serialization process. Note that when using binary serialization, the object is saved in its entirety. To work with binary serialization, you should include the System.Runtime.Serialization.Formatters.Binary namespace.

SOAP serialization

SOAP (Simple Object Access Protocol) serialization is a good choice when you would like to transfer objects from one application to another when these applications use heterogeneous architectures. In essence, the main advantage of using SOAP serialization is portability. SOAP serialization can be used to serialize an object in SOAP format. To work with SOAP serialization you should include the System.Runtime.Serialization.Formatters.Soap namespace in your program. Note that like XML Serialization, objects that are serialized using SOAP serialization are persisted as XML.

XML Serialization

XML Serialization is a type of serialization that is used to serialize the public members of an instance of a class into a XML stream. Note that XML serialization is slow compared to Binary serialization — actually it is much slower. The primary advantage of XML serializaton is that it provides cross — platform support and because it’s text-based, it is readable and can be edited as well. You can take advantage of XmlAttribute and set it on a property to enable the property to be serialized using XML serialization. The following code snippet illustrates how you can use XmlAttribute on a property.

[XmlAttribute("productName")]

public string ProductName

{

  get

  {

    return productName;

  }

  set

  {

    productName = value;

  }

}

To serialize and de-serialize an object using XML serialization you can use the XmlSerializer. The following code snippet shows how you can serialize an object using XML serialization — note how the XmlSerializer is used.

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Product));

using (TextWriter textWriter = new StreamWriter(@"D:Product.xml"))

 {

    xmlSerializer.Serialize(textWriter, productObject);

 }

Custom serialization

You can leverage custom serialization to control how an instance of a type can be serialized and deserialized. You can implement custom serialization by implementing the ISerializable interface. The ISerializable interface declares the GetObjectData() method. The following code snippet illustrates how you can implement custom serialization technique by implementing the ISerializable interface.

[Serializable]

public class Product : ISerializable

{

    public void GetObjectData(SerializationInfo info, StreamingContext context)

    {

        //Usual code

    }

}

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author