Serialization   



Serialization
is the process of writing the state of an object to a byte stream. This is useful when we want to save the state of our program to a persistent storage area, such as a file. At a later time we can restore these objects by using the process of deserialization.

As a simplest example of this we created an array of objects of class emp. We stored this data in a .dat file on the secondary storage and retrieved it using deserialization. Here is how the program will look

namespace serialize
{

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class emp
{

int id;
string name ;
double salary ;
public emp ( int i, string n, double s)
{

id = i ;
name = n ;
salary = s ;

}

public string ToString()
{

return id + " " + name + " " + salary ;

}

}

 

public class Class1
{

public static int Main ( string[] args )
{

emp[] e =
{

new emp ( 1, "Rahul", 4500 ),
new emp ( 2, "Janaki", 5345 ),
new emp ( 3, "Amol", 4460 ),
new emp ( 4, "Anil", 9456 ),
new emp ( 5, "Srikanth", 9500 ),
new emp ( 6, "Ravi", 5670 ),
new emp ( 7, "Abhijeet", 3345 ),
new emp ( 8, "prashant", 8500 )

} ;

 

File f = new File ( "C:\\emp.dat" ) ;
Stream s = f.Open ( FileMode.Create ) ;
BinaryFormatter b = new BinaryFormatter() ;

for ( int i = 0 ; i < e.Length ; i++ )
{

b.Serialize ( s, e[i] ) ;

}


s.Close();

s = f.Open(FileMode.Open);
for ( int i = 0 ; i < 8 ; i++)
{

emp ee = (emp)b.Deserialize(s);
Console.WriteLine ( ee.ToString() ) ;

}

s.Close();
return 0;

}

}

}

The Serializable attribute indicates that a class can be serialized. Here we intend to serialize the emp class so we should write it above the class definition. We created a new file emp.dat in the C drive and dumped the emp objects in it. Next we opened the same file and used the information for displaying. The BinaryFormatter class provides a way to serialize and deserialize an object, or an entire graph of connected objects; it uses a binary format for the serialized stream, which is both very compact, and fast to parse. Indicates that a class can be serialized