What is Serialization?
Serialization is the process of storing the state of an object to the stream of bytes. Using serialization one can store the object in to memory stream or file system in such a way that the original object can be retrieve from persistent medium using DeSerialization.
One can make the class serialize by adding [Serializable] attribute at the top of class and the dot net framework automatically serialize object of that class when ever required. For example you can store only serializable data in ViewState. So if you have a class which has [Serializable] attribute, the dot net framework automatically serialize it and store it in ViewState. You do not have to write any code for serialization.
In this article I used a Person class (shown in Fig - (1)) which has few fields with different datatypes. We will Serialize and Deserialize the object of Person class using CustomSerialization class (shown in Fig (2)).
Fig - (1) Person class which we will use for serialization.
One can add [NonSerialized] attribute for the field that one do not wants to serialize. You can see that we have used [NonSerialized] attribute to mstrPhone field.
Below is CustomSerialization class which includes the method for Serialization and DeSerialization. We need to import System.Runtime.Serialization and System.Runtime.Serialization.Formatters.Binary namespace.
Fig - (2) Custom Serialization class to serialize and deserialize the data.
Code shows a part of web page code behind which shows code for serialization.
Fig - (3) Web Page code behind class
One thing to note here is, the constructor of Person class will not called when the object is deserialize.
Happy Programming !!!