How to not shoot yourself in the foot when working with serialization

This article will be especially useful to those who are only starting to familiarize themselves with the serialization mechanism. More experienced programmers may also learn something interesting, or just be reassured that even professionals make mistakes.
 
However, it is assumed that the reader is already somewhat familiar with the serialization mechanism.
 
We should understand that the statements described in the article are relevant for some serializers, for example — BinaryFormatter and SoapFormatter; for others, which are manually written serializers, the behavior can be different. For example, the absence of the attribute [Serializable] for the class may not prevent serialization and deserialize it with a custom serializer.
 
Briefly summarizing all the information, we can formulate several tips and rules:
  • Annotate the types, implementing the ISerializable interface with the [Serializable] attribute.
  • Make sure that all members annotated by the [Serializable] attribute get correctly serialized;
  • Implementing the ISerializable interface, don't forget to implement the serialization constructor (Ctor(SerializationInfo, StreamingContext));
  • In the sealed types, set the access modifier private for a serialization constructor, in the unsealed — protected;
  • In the unsealed types implementing the ISerializable interface, make the GetObjectData method virtual;
  • Check that in the GetObjectData all the necessary members get serialized, including members of the base class if there are such.
We hope you will learn something new from this article, and will become a expert in the sphere of serialization. Sticking to the rules and following the tips that we have given above, you will save time debugging the program, and make life easier for yourself, and other developers working with your classes. PVS-Studio analyzer will also be of great help, allowing you to detect such errors right after they appear in your code.
 
Read more article you can find the link: http://www.viva64.com/en/b/0409/