Delving Deeper into Serialization with .NET - ISerializable
(Page 3 of 4 )
So far, the serialization process has been mostly handled for us. All that we've done is apply attributes where necessary, and .NET has figured out how to do everything on its own. Where we've needed to intervene and participate in the serialization and deserialization processes, we've created methods that are called at the proper time. This automation is generally a good thing. However, it is possible to gain more direct control over the processes of serialization and deserialization. This can be done by implementing the ISerializable interface.
Recall from the previous part how we needed more control over the User class. The class defined a DateTime called sessionStartTime that was marked with the NonSerialized attribute. Since the value of this member isn't stored, we needed to give it an appropriate value upon deserialization. This was accomplished through the OnDeserializing attribute and a simple method. The method, called during the deserialization process, set sessionStartTime to the current date and time. This got the job done, but we could also have implemented ISerializable. Let's revisit the example and reconstruct User to implement ISerializable. Here is the original User class, without the OnDeserializing fix:
using System;
[Serializable]
public class User
{
private string name;
private DateTime sessionStartTime;
public User(string name)
{
this.name = name;
sessionStartTime = DateTime.Now;
}
public string Name
{
get
{
return name;
}
}
public DateTime SessionStartTime
{
get
{
return sessionStartTime;
}
}
}
Before, because we did not want sessionStartTime to be serialized, we applied the NonSerialized attribute, which prevented .NET from storing the field's value. Now, however, we don't have to apply the attribute. The ISerializable interface defines a method called GetObjectData. In this method, we specify exactly what is to be serialized and how. Only what we specify to be serialized is serialized; everything else is not. Here are the changes required for User to implement the ISerializable interface:
...
using System.Runtime.Serialization;
[Serializable]
public class User : ISerializable
{
...
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("name", name, typeof(string));
}
}
Notice that GetObjectData has no return type and accepts two parameters: a SerializationInfo and a StreamingContext. The former is what's important here. It contains (or needs to contain, rather) information about the members to be serialized. To add data, the AddValue method is called, which accepts the name of the data, the value of the data and the type of the data. Here, we specify that the name field is to be serialized. Also, it's important that the method be virtual, as we'll see later.
Next: Deserialization >>
More .NET Articles
More By Peyton McCullough