Example of IDeserializationCallback.OnDeserialization implementation

To prevent a data member from being serialized, we would mark it with the [NonSerialized] attribute.

Example:

[NonSerialized] public decimal total;

To enable your class to initialize a nonserialized member automatically, use the IDeserializationCallback interface and then implement IDeserializationCallback.OnDeserialization. Each time your class is deserialized, the runtime calls the IDeserializationCallback.OnDeserialization method after deserialization is complete.

[Serializable]
class ShoppingCartItem : IDeserializationCallback {
    public int productId;
    public decimal price;
    public int quantity;
    [NonSerialized] public decimal total;
    public ShoppingCartItem(int _productID, decimal _price, int _quantity)
    {
        productId = _productID;
        price = _price;
        quantity = _quantity;
        total = price * quantity;
    }
    void IDeserializationCallback.OnDeserialization(Object sender)
    {
        // After deserialization, calculate the total
        total = price * quantity;
    }
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.