Appendix W Serialization

This appendix summarizes useful serialization topics and techniques.

XML Serialization

To serialize and deserialize objects in XML format, you use the XmlSerializer class’s Serialize and Deserialize methods. The methods work only for classes that have a parameterless constructor, either the default constructor or one that you created. They also work only for public properties and fields. All other properties and fields are ignored.

To serialize an object, follow these steps.

  1. Create an XmlSerializer, passing its constructor the object’s type.
  2. Create a TextWriter to hold the serialization.
  3. Call the serializer’s Serialize method, passing it the TextWriter and the object to serialize.

The following code shows how a program might serialize a Customer object.

// Create a serializer that works with the Customer class.
XmlSerializer serializer = new XmlSerializer(typeof(Customer));

// Create a TextWriter to hold the serialization.
string serialization;
using (TextWriter writer = new StringWriter())
{
    // Serialize the Customer.
    serializer.Serialize(writer, customer);
    serialization = writer.ToString();
}

// Display the serialization.
serializationTextBox.Text = serialization;

To deserialize a serialization, follow these steps.

  1. Create an XmlSerializer, passing its constructor the object’s type.
  2. Create a TextReader from which to read the serialization.
  3. Call the serializer’s Deserialize method, passing it the TextReader. Cast the result into the object’s type.

Get C# 5.0 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.