Serialization Events in .NET Framework

.NET Framework supports binary serialization. Picture pretty much self explanatory.

Any time you want to call on a method during these events you need to remember that method should accept StreamingContect object as a parameter. Method should return void and method should have the attribute that matches the event you are trying to intercept.
class ShoppingCartItem
    public Int32 myProductId;
    publicdecimal myPrice;
    public Int32 myQuantity;
    publicdecimal myTotal;
    void CalculateTotal(StreamingContext sc)
        myTotal = myPrice * myQuantity;
    void CheckTotal(StreamingContext sc)
        if (myTotal == 0) { CalculateTotal(sc); }

Serialization and Deserialization does not matter for the destination however you may serialize or deserialize object differently based on your requirement. You do this by examining StreamingContext structure. It has two notable properties

  • Context – which is a reference to an object that contains any user-desired context info.
  • State – which is a set of bit flags indicating the source or destination.
    • The flags are: CrossProcess, CrossMachine, File, Resistance, Remoting, Other, Close, CrossAppDomain.