Search code examples
c#serializationdeserializationserializable

Serializable class with ISerializable constructor


Is it possible to declare the class [Serializable], and yet add a constructor with the signature (SerializationInfo information, StreamingContext context) to do some specific task at the time of deserialization?


Solution

  • You can either inherit ISerializable or just add a couple custom methods to your class that are called during serialization/deserialization.

    These methods are decorated with special attributes that tell the serializer to call them:

    OnDeserializedAttribute

    OnDeserializingAttribute

    OnSerializedAttribute

    OnSerializingAttribute

    MSDN has a great tutorial (which I don't need to duplicate here) on how to use these attributes:

    https://msdn.microsoft.com/en-us/library/ty01x675%28v=vs.110%29.aspx and see the links provided for each attribute for implementing methods for each.