Wednesday, April 15, 2009

IDeserializationCallBack Interface

When we don't want to serialize some field, and this field is normally dependent on some other field and for the reason of performance concern, we don't serialize them, we use IDeserialization Interface.


For example:
[Serializable]
class Rectangle: IDeserializationCallBack
{
public decimal length;
public decimal width;
[NonSerialized] public decimal area;

publc Rectangle(decimal _length,decimal width)
{
length=_length;
width=_width;
area=length*width;
}

void IdeserializationCallback.OnDeserilization(Object sender)
{
//after deserialization, calculate the area
area=length*width;
}
}

Each time your class is deserialized, the runtime call the IDeserializationCallback.OnDeserialization method after deserialization is complete.

Here is a quick test code:
new Rectangle(50.00, 20.0).Serialize(@"D:\test.txt");
Rectangle rt=new Rectangle();
rt.Deserialize(@"D:\test.txt");
Console.WriteLine(rt);

No comments: