Serialization
It’s a process of persisting the state of an object to disk or any storage medium.
Why Serialization?
- To re-create the object at a later stage.
- To send object across application domains.
How to make a class serializable?
By using the [Serializable] attribute
[Serializable]
class Employee
{
public int age;
public string name;
}
How to serialize a serializable class?
//Initialize the object
Employee emp=new Employee();
emp.age=30;
emp.name="Mohammed Ajmal";
//Serialize the object
IFormatter formatter=new BinaryFormatter();
Stream stream=new FileStream("SerializedData.dat",
FileMode.Create,
FileAccess.Write,
FileShare.None);
formatter.Serialize(stream,emp);
stream.Close();
//Deserialize object and read values
Stream deserStream=new FileStream("SerializedData.dat",
FileMode.Open,
FileAccess.Read,
FileShare.Read);
Employee deserializedEmp=(Employee) formatter.Deserialize(deserStream);
deserStream.Close();
//Write the deserialized data
Console.WriteLine("Age = {0}",deserializedEmp.age);
Console.WriteLine("Name = {0}",deserializedEmp.name);
Note: 1. If portability is required use SoapFormatter instead of BinaryFormatter
2. The Serializable attribute cannot be inherited
How to prevent few member variables from being serialized?
Use the [NonSerialized] attribute with the member variable
Ex. [NonSerialized] public string name;