Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
For examples of serialization, see Related Topics and Examples later in this topic.
The object is serialized to a stream, which carries not just the data, but information about the object’s type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.
Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. A SerializationException exception is thrown if you attempt to serialize but the type does not have theSerializableAttribute attribute.
If you do not want a field within your class to be serializable, apply the NonSerializedAttribute attribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and the field cannot be meaningfully reconstituted in a different environment, then you may want to make it nonserializable.
If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will also be serialized.
You can apply attributes to classes and class members in order to control the way the XmlSerializerserializes or deserializes an instance of the class.
When you use basic serialization, the versioning of objects may create problems, in which case custom serialization may be preferable. Basic serialization is the easiest way to perform serialization, but it does not provide much control over the process.
If you want your object to be deserialized in a custom manner as well, you must use a custom constructor.
- Walkthrough: Persisting an Object (C# and Visual Basic)
- Demonstrates how serialization can be used to persist an object’s data between instances, allowing you to store values and retrieve them the next time the object is instantiated.
- How to: Read Object Data from an XML File (C# and Visual Basic)
- Shows how to read object data that was previously written to an XML file using the XmlSerializer class.
- How to: Write Object Data to an XML File (C# and Visual Basic)
- Shows how to write the object from a class to an XML file using the XmlSerializer class.