Serialization and Deserialization in C#

What is Serialization in C#?

 
Serialization in C# is the process of bringing an object into a form that it can be written on stream. It's the process of converting the object into a form so that it can be stored on a file, database, or memory; or, it can be transferred across the network. Its main purpose is to save the state of the object so that it can be recreated when needed.
 
serialization 
 

What is Deserialization in C#?

 
As the name suggests, deserialization in C# is the reverse process of serialization. It is the process of getting back the serialized object so that it can be loaded into memory. It resurrects the state of the object by setting properties, fields etc.
 
Types 
  • Binary Serialization
  • XML Serialization
  • JSON Serialization 
Example
 
Here I will be giving you an example of how to serialize and deserialize an object using binary formatter or xml formatter.
 
Create a new Windows Form Application and add few controls to it as shown below.
 
form 
 
Now make a class named Employee:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace WindowsFormsApplication1  
  8. {  
  9.     [Serializable]  
  10.     public class Employee  
  11.     {  
  12.         private string Name;  
  13.   
  14.         public string name  
  15.         {  
  16.             get  
  17.             {  
  18.                 return Name;  
  19.             }  
  20.   
  21.             set  
  22.             {  
  23.                 Name = value;  
  24.             }  
  25.         }  
  26.   
  27.         private string Phone;  
  28.   
  29.         public string phone  
  30.         {  
  31.             get  
  32.             {  
  33.                 return Phone;  
  34.             }  
  35.   
  36.             set  
  37.             {  
  38.                 Phone = value;  
  39.             }  
  40.         }  
  41.   
  42.         private DateTime DoB;  
  43.   
  44.         public DateTime dob  
  45.         {  
  46.             get  
  47.             {  
  48.                 return DoB;  
  49.             }  
  50.   
  51.             set  
  52.             {  
  53.                 DoB = value;  
  54.             }  
  55.         }  
  56.   
  57.         private string Department;  
  58.   
  59.         public string department  
  60.         {  
  61.             get  
  62.             {  
  63.                 return Department;  
  64.             }  
  65.   
  66.             set  
  67.             {  
  68.                 Department = value;  
  69.             }  
  70.         }  
  71.           
  72.         private int Salary;  
  73.   
  74.         public int salary  
  75.         {  
  76.             get  
  77.             {  
  78.                 return Salary;  
  79.             }  
  80.   
  81.             set  
  82.             {  
  83.                 Salary = value;  
  84.             }  
  85.         }  
  86.   
  87.         [NonSerialized]  
  88.         public string additionalInfo;  
  89.     }  
  90. }  
Put [Serializable] on top of the class. For those attributes which you don't want to serialize put [NonSerialized] on them.
 
Add a click event for Serialize button. When clicking on the serialize button we want to serialize the object of class Employee and store it in a file named "employee.binary".
  1. private void Serialize_Click(object sender, EventArgs e)  
  2. {  
  3.     Employee emp = new Employee {  
  4.         name = textBoxName.Text,  
  5.         phone = textBoxPhone.Text,  
  6.         dob = dateTimePickerDoB.Value,  
  7.         department = textBoxDepartment.Text,  
  8.         salary = Convert.ToInt32(textBoxSalary.Text),  
  9.         additionalInfo = "We don't want it to serialize"  
  10.     };  
  11.   
  12.     BinaryFormatter bf = new BinaryFormatter();  
  13.   
  14.     FileStream fsout = new FileStream("employee.binary", FileMode.Create, FileAccess.Write, FileShare.None);  
  15.     try  
  16.     {  
  17.         using (fsout)  
  18.         {  
  19.             bf.Serialize(fsout, emp);  
  20.             label6.Text = "Object Serialized";  
  21.         }  
  22.     }  
  23.     catch  
  24.     {  
  25.         label6.Text = "An error has occured";  
  26.     }  
  27. }  
Use BinaryFormatter to serialize the object in BinaryFormat. Make a file using FileStream named "employee.binary". In this file your serialized object will be stored. bf.Serialize(fsout, emp) will serialize the object "emp" and store it in file "employee.binary".
 
The next thing is to write the code to deserialize the object. Add a click event for Deserialize button. When clicking on the Deserialize button we want to deserialize the object and show its values on screen.
  1. private void Deserialize_Click(object sender, EventArgs e)  
  2. {  
  3.     Employee emp = new Employee();  
  4.   
  5.     BinaryFormatter bf = new BinaryFormatter();  
  6.   
  7.     FileStream fsin = new FileStream("employee.binary", FileMode.Open, FileAccess.Read, FileShare.None);  
  8.     try  
  9.     {  
  10.         using (fsin)  
  11.         {  
  12.             emp = (Employee) bf.Deserialize(fsin);  
  13.             label6.Text = "Object Deserialized";  
  14.   
  15.             textBoxName.Text = emp.name;  
  16.             textBoxPhone.Text = emp.phone;  
  17.             dateTimePickerDoB.Value = emp.dob;  
  18.             textBoxDepartment.Text = emp.department;  
  19.             textBoxSalary.Text = emp.salary.ToString();  
  20.         }  
  21.     }  
  22.     catch  
  23.     {  
  24.         label6.Text = "An error has occured";  
  25.     }  
  26. }  

Use BinaryFormatter to deserialize the object from file "employee.binary". After the object is deserialized update the values of text boxes.

Now let's execute our program and add some values to text boxes as shown below.
 
 
Click on Serialize.
 
 
 
The message says that the object is serialized. To make sure that it is serialized go to,
 
WindowsFormsApplication\WindowsFormsApplication\bin\Debug\employee.binary

Here you will find the file.
 
 
 
Now to deserialize the object, remove the text from the text boxes and change the date to something else.
 
 
 
Click on Deserialize and you will get the following.
 
 
 
Serialize object in XML format,
 
For xml serialization use XmlSerializer instead of BinaryFormatter.
  1. XmlSerializer xs = new XmlSerializer(typeof(Employee));      
Change the filename from "employee.binary" to "employee.xml".
 
and use [Xmlgnore] instead of [NonSerialized] in Employee class. The rest will be the same.