Custom Serialization with .NET Framework
You can always go extra mile with the serialization and implement your own custom serialization by overriding built in serialization implementation. You do that with the help of ISerializable interface and applying Serializable attribute to the class of interest. Implementing ISerializable interface will require you to use GetObjectData method and constructor that is used for the deserialization. They both will be called during serialization and during Deserialization correspondingly. You also need to use following name spaces for this task: System.Runtime.Serialization and System .Security.Permissions SerializationInfo plays major role is serializing class.
class ShoppingCartItem : ISerializable
{
public Int32 myProductId;
public decimal myPrice;
public Int32 myQantity;
[NonSerialized]
public decimal myTotal;
public ShoppingCartItem(int _myProductID, decimal _myPrice, int _myQuantity)
{
myProductId = _myProductID;
myPrice = _myPrice;
myQantity = _myQuantity;
myTotal = myPrice * myQantity;
}
protected ShoppingCartItem(SerializationInfo info, StreamingContext context)
{
myProductId = info.GetInt32("Prod ID");
myPrice = info.GetDecimal("Price");
myQantity = info.GetInt32("Qty");
myTotal = myPrice * myQantity;
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Prod ID", myProductId);
info.AddValue("Price", myPrice);
info.AddValue("Qty", myQantity);
}
public override string ToString()
{
return myProductId + ": " + myPrice + " × " + myQantity + " = " + myTotal;
}
}