ISerializable implementation example
Introduction
Some times, we need to record data according to a given object into a file in order to either stock them or to send them via network, and such task are very needed especially in the asp or the distributed applications case. This kind of task is called serialization. There are several methods to do that, but never the less, I give one alternative among them as a part of this article. This method consists on implementing the ISerializable interface.
Let's consider a class who's called Person and here is its description:
Figure 1
The Person class code is as follow:
public class Person
{
private string _FirstName;
private string _LastName;
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public Person()
{
}
public Person(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}
}
To serialize objects issued from this class, we should implement the ISerializable interface; this last one has a method ISerializable.GetObjectData that it should be implemented.
This is how to implement the ISerializable interface:
public class Person:ISerializable
{
private string _FirstName;
private string _LastName;
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public Person()
{
}
public Person(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}
void ISerializable.GetObjectData(SerializationInfo oInfo, StreamingContext oContext)
{
oInfo.AddValue("FirstName", this.FirstName);
oInfo.AddValue("LastName", this.LastName);
}
}
The GetObjectData ( ) method hasn't to be marked as public otherwise an error indicates that the modifier public in not valid for this item will be generated.
No comments:
Post a Comment