Object Serialization: What It Is and Why It’s Needed
Object serialization is a mechanism whereby you can store a given object beyond the lifetime of its containing program. In other words, the object can outlive the program that creates it and then be resurrected for reuse at a later time. In a nutshell, you use serialization to save the object to a Stream-derived type, such as a physical file or a memory location (using MemoryStream).
Regardless of the serialization format you use (I’ll return to this topic later), there are several reasons why you might want to store the state of an object. For example:
- The object reflects a lot of user-specific data. An obvious example is when a given application runs an interactive wizard. The data collected by the wizard might be very detailed and needed for subsequent access. This makes it a candidate for serialization.
- You want to transfer the object to another machine. This example is a little more interesting. Suppose you have an object that you want to move across a network—for instance, from a C# application into a Java application. In this case, you want to transfer the essential attributes and methods for a given object.
This leads us to an important point about C# serialization: The binary format records the full class hierarchy, which makes it somewhat .NET-centric. If you prefer a less restricted form of serialization mechanism, you can opt for the Simple Object Access Protocol (SOAP) format or for the XML format.
That’s enough theory for the moment. Let’s see some serialization code in action!