In some cases, the default serialization techniques provided
by .NET may not be sufficient in real life. This is when we require implementing
custom serialization. It is possible to implement custom serialization in .NET
by implementing the ISerializable interface. This interface allows an object
to take control of its own serialization and de-serialization process. It
gives us a great deal of flexibility in the way we can save and restore
objects. The ISerializable interface consists of a single method, GetObjectData,
which accepts two parameters.
The SerializationInfo class serves as the container for all the
data we want to serialize. The AddValue method is called to add the objects we
want to serialize to this container. The implementing class needs to have the
GetObjectData method and a special constructor which is used by the common
language runtime during the process of de-serialization. The following code listing
shows how we can implement Custom Serialization.
Listing 9:
public class Employee: ISerializable
{
private int empCode;
private string empName;
protected Employee(SerializationInfo serializationInfo, StreamingContext
streamingContext)
{
this.empCode = serializationInfo.GetInt32("empCode");
this.empName = serializationInfo.GetString("empName");
}
public void ISerializable.GetObjectData(SerializationInfo serializationInfo,
StreamingContext streamingContext)
{
serializationInfo.AddValue("empCode", this.empCode);
serializationInfo.AddValue("empName", this.empName);
}
}
The following listing shows how we can implement Custom
Serialization on a Custom Collection class that extends the CollectionBase
class of the System.Collections namespace.
Listing 10
[Serializable]
public class EmployeeCollection: System.Collections.CollectionBase,
ISerializable
{
private int empCode;
public EmployeeCollection()
{
empCode = 1;
}
protected EmployeeCollection(SerializationInfo info, StreamingContext context)
: base(info, context)
{
empCode = info.GetInt32("empCode");
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext
context)
{
base.GetObjectData(info, context);
info.AddValue("empCode", empCode);
}
}