Version-Tolerant Serialization Callbacks


The data contract programming model fully supports the version-tolerant serialization callback methods that the BinaryFormatter and SoapFormatter classes support.

There are four callback attributes. Each attribute can be applied to a method that the serialization/deserialization engine calls at various times. The table below explains when to use each attribute.

AttributeWhen the corresponding method is called
OnSerializingAttributeCalled before serializing the type.
OnSerializedAttributeCalled after serializing the type.
OnDeserializingAttributeCalled before deserializing the type.
OnDeserializedAttributeCalled after deserializing the type.

The methods must accept a StreamingContext parameter.

These methods are primarily intended for use with versioning or initialization. During deserialization, no constructors are called. Therefore, data members may not be correctly initialized (to intended default values) if the data for these members is missing in the incoming stream, for example, if the data comes from a previous version of a type that is missing some data members. To correct this, use the callback method marked with the OnDeserializingAttribute, as shown in the following example.

You can mark only one method per type with each of the preceding callback attributes.


    // The following Data Contract is version 2 of an earlier data 
    // contract.
    public class Address
        public string Street;

        public string State;

        // This data member was added in version 2, and thus may be missing 
        // in the incoming data if the data conforms to version 1 of the 
        // Data Contract. Use the callback to add a default for this case.
        public string CountryRegion;

        // This method is used as a kind of constructor to initialize
        // a default value for the CountryRegion data member before 
        // deserialization.
        private void setDefaultCountryRegion(StreamingContext c)
            CountryRegion = "Japan";

Version Tolerant Serialization