O'Reilly logo

C# 5.0 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required