In this article you will learn about serialization and deserialization In C#.
What is Serialization? Serialization 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.
As the name suggests, deserialization 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.
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.
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".
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.
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.
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.
For xml serialization use XmlSerializer instead of BinaryFormatter.
and use [Xmlgnore] instead of [NonSerialized] in Employee class. The rest will be the same.
Object Oriented Programming Using C#