Serialization and De-Serialization in .Net
I have recently gone through a training and came to know what actually serialization & De-Serialization is. Before this as per my understanding serialization was the process of writing stream of byte(s) of objects into physical storage & De-Serialization is vice-versa i.e. reading byte(s) of stream from physical storage and converting them into corresponding objects , and in most of the Interviews I gave this answer only and Interviewer was not satisfied at all.
Let’s define Serialization in new way now. It may be defined as “Process of storing object state in file(s) by means of predefined formatters/serializers”. Using these predefined formatters objects get saved into file and later it can be retrieved and de-serializes using the corresponding formatters.
Now question comes why we need serialization? What is the use of Serialization?
There are many situations where objects directly cannot be transferred from one state to another state or we can say in web services/remoting we cannot directly transfer objects over network, it needs to be serialize and after receiving it on other end it will be de-serialized and used as an object.
Second situation is like if we are calling an object and this object again calling other resources and it becomes suppose 500 MB. SO for every call there will be a 500 MB object in memory which will reduce the performance certainly. So to overcome this issue, once the object is called and data is collected, we can persist the state of the object in some physical storage and whenever require, it can be de-serialized and will be used as an object.
.Net framework provides many serializers for storing object state. Some of them are Binary Serilizer, XML Serializer and Custom Serializer. There are many more serializers available in .net framework but I am not going to cover all those, you can explore these on Google.
Some of the most used formatters are :
- Binary Formatter
- XML Serializer
- Custom Srializer
Let’s see an example of Binary formatter, for this I will create a console application in Visual Studio. I suppose you know how to create console application in VS. You can also create windows forms of web application also, you just need to call methods on some actions like page load or form load or some button clicks.
First and very important thing to know before starting this demo is Attribute base programming, if you then its good else I will post a new blog post regarding Attribute base programming. For now we will create a class with some public properties and one parameterized constructor and will add one attribute to this class which will make it serializable. The class will looks like:
We will create an instance of this class by providing values to its constructor. Code looks like:
In the above method, we are using BinaryFormatter class which is present in System.Runtime.Serialization.Formatters.Binary namespace, so you have to include it in your code. So the above code will serialize the object of the class MyClassForSerialization with data provided in the constructor. When you will call this method a file will be created at the given path and if you will open this file you will see some garbage data. See below figure:
If any confusion you have understanding this code then let me know. Provide your questions and suggestions as a comment. Now let’s create a method to De-Serialize the above object. So for this we have to read the file where object is stored, in this case it is “C:\\tt\BinaryObject.bin”.
In the above code Binary formatter is taking stream from file and de-serializing it to an object and we are type casting this object to our known object. When you will call this method you will get the data you have provided during the serialization of this object.
Let’s call both method in the main class and see the output in the console.

If we combine whole code, it looks like:
First and very important thing to know before starting this demo is Attribute base programming, if you then its good else I will post a new blog post regarding Attribute base programming. For now we will create a class with some public properties and one parameterized constructor and will add one attribute to this class which will make it serializable. The class will looks like:
[Serializable] class MyClassForSerialization { public string FullName { get; set; } public int Age { get; set; } public MyClassForSerialization(string fName,int age) { this.FullName = fName; this.Age = age; } }Now we will serialize and de-serialize this class in the main method of the console application we have created. Let’s create two static methods, one for serialization and another for de-serialization.
We will create an instance of this class by providing values to its constructor. Code looks like:
private static void Serialize() { Console.WriteLine("Serializing Class MyClassForSerialization"); MyClassForSerialization objClass = new MyClassForSerialization("Test Name", 28); BinaryFormatter formatter = new BinaryFormatter(); using (FileStream fs = new FileStream(@"C:\tt\BinaryObject.bin", FileMode.Create)) { formatter.Serialize(fs, objClass); } Console.WriteLine("Class MyClassForSerialization Serialized Successfully"); }
In the above method, we are using BinaryFormatter class which is present in System.Runtime.Serialization.Formatters.Binary namespace, so you have to include it in your code. So the above code will serialize the object of the class MyClassForSerialization with data provided in the constructor. When you will call this method a file will be created at the given path and if you will open this file you will see some garbage data. See below figure:


If any confusion you have understanding this code then let me know. Provide your questions and suggestions as a comment. Now let’s create a method to De-Serialize the above object. So for this we have to read the file where object is stored, in this case it is “C:\\tt\BinaryObject.bin”.
private static void DeSerialize() { Console.WriteLine("De-Serializing Class MyClassForSerialization"); BinaryFormatter deFormatter = new BinaryFormatter(); using (FileStream fs = new FileStream(@"C:\tt\BinaryObject.bin", FileMode.Open)) { MyClassForSerialization obj = deFormatter.Deserialize(fs) as MyClassForSerialization; Console.WriteLine("Class MyClassForSerialization De-Serialized Successfully"); Console.WriteLine("Values stored in the object is FullName: '{0}' and Age : '{1}'", obj.FullName, obj.Age); } }
In the above code Binary formatter is taking stream from file and de-serializing it to an object and we are type casting this object to our known object. When you will call this method you will get the data you have provided during the serialization of this object.
Let’s call both method in the main class and see the output in the console.
static void Main(string[] args) { Serialize(); DeSerialize(); Console.ReadLine(); }When we will run this program we will get below result:

If we combine whole code, it looks like:
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace SerializationDemo { class Program { static void Main(string[] args) { Serialize(); DeSerialize(); Console.ReadLine(); } private static void Serialize() { Console.WriteLine("Serializing Class MyClassForSerialization"); MyClassForSerialization objClass = new MyClassForSerialization("Test Name", 28); BinaryFormatter formatter = new BinaryFormatter(); using (FileStream fs = new FileStream(@"C:\tt\BinaryObject.bin", FileMode.Create)) { formatter.Serialize(fs, objClass); } Console.WriteLine("Class MyClassForSerialization Serialized Successfully"); } private static void DeSerialize() { Console.WriteLine("De-Serializing Class MyClassForSerialization"); BinaryFormatter deFormatter = new BinaryFormatter(); using (FileStream fs = new FileStream(@"C:\tt\BinaryObject.bin", FileMode.Open)) { MyClassForSerialization obj = deFormatter.Deserialize(fs) as MyClassForSerialization; Console.WriteLine("Class MyClassForSerialization De-Serialized Successfully"); Console.WriteLine("Values stored in the object is FullName: '{0}' and Age : '{1}'", obj.FullName, obj.Age); } } } [Serializable] class MyClassForSerialization { public string FullName { get; set; } public int Age { get; set; } public MyClassForSerialization(string fName,int age) { this.FullName = fName; this.Age = age; } } }I will explain XML and custom serializers in next blog post. Any questions/Comments are welcomed.
Download this article as a Word Doc

Ahaa, its good conversation on the topic of this post here at this web site, I have read all that, so now me also commenting here.
ReplyDeleteAlso visit my web-site - new mother advice
Nice Article...Thanks for sharing
ReplyDelete