13.6. Serialization and Deserialization

In OOP programs, reading and writing an object's data (like myData in the previous section) is so common that C# provides a simple mechanism for those tasks. After all, in the previous program, each time you wrote a new friend's information to disk you were actually saving the state of the clsRandomAccess object named myData to disk. Simply stated, serialization is the act of saving, or persisting, an object's state to disk. Deserialization is the act of reconstructing an object's state by reading the information stored on disk back into an object of that class.

Because the primitive data types (byte, char, int, long, double, string, and so on) are not serializable by default, you must explicitly state that the object can be serialized using the [Serializable] attribute at the top of the class source file of the object to be serialized.

Time-Saving Tip

If you fail to mark a class as serializable using the [Serializable] attribute before you compile the program, the program will fail. The error message tells you that one (or more) of the class members does not have the [Serializable] attribute set. If you see this error message, going back and adding [Serializable] to the class file does no good. Moral of the story: don't forget to add the [Serializable] attribute to the class file before you compile it.

Try It Out: Serialization-Deserialization

Figure 13-12 shows a sample run of a program that uses serialization.

Figure 13-12. Figure ...

Get Beginning C# 3.0 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.