Serialization can be of the following types:
·
Binary Serialization
·
SOAP Serialization
·
XML Serialization
·
Custom Serialization
All these types of serialization are explained in details in
the sections that follow.
Binary Serialization
Binary serialization is a mechanism which writes the data to
the output stream such that it can be used to re-construct the object
automatically. The term binary in its name implies that the necessary information
that is required to create an exact binary copy of the object is saved onto the
storage media. A notable difference between Binary serialization and XML
serialization is that Binary serialization preserves instance identity while
XML serialization does not. In other words, in Binary serialization the entire
object state is saved while in XML serialization only some of the object data
is saved. Binary serialization can handle graphs with multiple references to
the same object; XML serialization will turn each reference into a reference to
a unique object. The following code listing shows how we can implement binary
serialization.
Listing 2:
public void BinarySerialize(string filename, Employee emp)
{
FileStream fileStreamObject;
try
{
fileStreamObject = new FileStream(filename, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStreamObject, emp);
}
finally
{
fileStreamObject.Close();
}
}
The following code listing shows how we can implement binary
de-serialization.
Listing 3:
public static object BinaryDeserialize(string filename)
{
FileStream fileStreamObject;
try
{
fileStreamObject = new FileStream(filename, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (binaryFormatter.Deserialize(fileStreamObject));
}
finally
{
fileStreamObject.Close();
}
}