Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
Example 1
Explanation
Here we have our own class named ClassToSerialize. This class has two public valiables name and age with some default values. We will write this class to a disk file (temp.dat) using SerializeTest class.
SerializeTest class has two methods SerializeNow() and DeSerializeNow() which perform the task of serialization and deserialization respectively.
The general steps for serializing are,
The steps for de-serializing the object are similar. The only change is that you need to call deserialize method of BinaryFormatter object.
Now, let us see an example where we have used 'real' class with public and shared members and properties to encapsulate them. The class also uses another supporting class. This is just to make clear that if your class contains further classes, all the classes in the chain will be serialized.
Example 2
Example 3 The final example shows how to serialize array of objects.
View All