How to implement ISerializable, the serialization constructor, and the GetObjectData method

Implementing ISerializable involves implementing the GetObjectData method and a special constructor that is used when the object is deserialized. The runtime calls GetObjectData during serialization, and the serialization constructor during deserialization.
When the runtime calls GetObjectData during serialization, you are responsible for populating the SerializationInfo object that is provided with the method call. Simply add the variables to be serialized as name/value pairs using the AddValue method, which internally creates SerializationEntry structures to store the information.

[Serializable]
class ShoppingCartItem : ISerializable
{
public Int32 productId;
public decimal price;
public Int32 quantity;
[NonSerialized]
public decimal total;
 
// The standard, non-serialization constructor
public ShoppingCartItem(int _productID, decimal _price, int _quantity)
{
productId = _productID;
price = _price;
quantity = _quantity;
total = price * quantity;
}
 
// The following constructor is for deserialization
protected ShoppingCartItem(SerializationInfo info,StreamingContext context)
{
productId = info.GetInt32("Product ID");
price = info.GetDecimal("Price");
quantity = info.GetInt32("Quantity");
total = price * quantity;
}
 
// The following method is called during serialization
[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
public virtual void GetObjectData(SerializationInfo info,StreamingContext context)
{
info.AddValue("Product ID", productId);
info.AddValue("Price", price);
info.AddValue("Quantity", quantity);
}
 
public override string ToString()
{
return productId + ": " + price + " x " + quantity + " = " + total;
}
}
Share Article/Example:
  • Facebook
  • Twitter
  • del.icio.us
  • Digg
  • DotNetKicks
  • DZone