Delving Deeper into Serialization with .NET - Deserialization
(Page 4 of 4 )
Now, an instance of User can be serialized. However, we need to provide a way for an object to be deserialized as well; this is not done for us. We have to pull our value back out and assign it to the proper place. Additionally, we need to give sessionStartTime a value as well. This is all done through a constructor, whose parameters match the parameters of GetObjectData. The constructor is automatically called upon deserialization, and if it's absent, an exception will be raised. Here's the required code:
public class User : ISerializable
{
...
protected User(SerializationInfo info, StreamingContext context)
{
name = info.GetString("name");
sessionStartTime = DateTime.Now;
}
...
}
Notice how the new constructor is protected. This is to prevent an external source from manipulating private data. Otherwise, information could be loaded with undesirable values.
Now, User is ready for serialization and deserialization:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class UsingISerializable
{
public static void Main(string[] args)
{
// Create a User
User dan = new User("Dan");
Console.WriteLine("{0}, logged on since {1}.", dan.Name, dan.SessionStartTime);
// Serialize dan
MemoryStream myStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(myStream, dan);
// Deserialize dan
myStream.Position = 0;
dan = (User)formatter.Deserialize(myStream);
myStream.Close();
Console.WriteLine("{0}, logged on since {1}.", dan.Name, dan.SessionStartTime);
}
}
Dan, logged on since 8/3/2007 7:09:58 PM.
Dan, logged on since 8/3/2007 7:09:59 PM.
Earlier, we looked at inheritance with .NET's automatic method of serialization. .NET handled the private data defined by our sample base class, Shape. However, with ISerializable, this isn't the case. For a child class to be properly serialized, it needs to override GetObjectData, wherein it needs to call its base class' GetObjectData method (this is why we set User's as virtual). The child class also needs to call its parent class' constructor. Let's create a class called Administrator, which will inherit from User, to demonstrate this:
[Serializable]
public class Administrator : User
{
public Administrator(string name)
: base(name)
{
// initialize data
}
protected Administrator(SerializationInfo info, StreamingContext context)
: base(info, context)
{
// restore data
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
// add data to info
}
}
So, why use ISerializable over .NET's default method of serialization? Actually, in most cases, you shouldn't. As you've probably noticed, using ISerializable is far more complicated and messier, and it's actually slower. Unless you have a really good reason to use ISerializable, stick with the default method. If you need control over the serialization and deserialization processes, simply use the attributes discussed in the last part. Moreover, the attribute approach is more readable. Rather than looking through the GetObjectData method to discover what members are serialized and what members are not, one can just look at the member itself.
Conclusion
Serialization is a powerful technique for persisting objects. In the first part, we examined how to use .NET's default, attribute-based serialization method, and we saw how to participate in this process by using special attributes and methods. In this part, we looked at how inheritance affects the serialization process. We also looked at the ISerializable interface, which offers a more manual approach to serialization. However, serialization does not end there: there are many more serialization-related features to the framework that merit looking into.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |