03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

564 ❘ CHAPTER 25 Serialization<br />

This chapter explains serialization. It explains how to serialize and deserialize objects. It also<br />

explains attributes that you can use to control how objects of a particular class are serialized.<br />

The .NET Framework gives you three choices for how data is stored in a serialization: XML data,<br />

JSON data, or binary data. The following sections explain how you can use each of these three choices.<br />

Serialization Namespaces<br />

The System.Xml.Serialization namespace includes XML serialization classes.<br />

To make that kind of serialization easier, you may want to include the following<br />

using directive in your code.<br />

using System.Xml.Serialization;<br />

The System.Runtime.Serialization.Json namespace includes JSON serialization<br />

classes. To make that kind of serialization easier, you may want to include the<br />

following using directive in your code.<br />

using System.Runtime.Serialization.Json;<br />

The JSON classes are included in the System.ServiceModel.Web library. If you<br />

will be using those classes, use Project ➪ Add <strong>Reference</strong> to add a reference to that<br />

library to your project.<br />

XML Serialization<br />

To serialize and deserialize objects in XML format, you use the XmlSerializer class’s Serialize<br />

and Deserialize methods. The methods work only for classes that have a parameterless constructor,<br />

either the default constructor or one that you created. They also work only for public properties<br />

and fields. All other properties and fields are ignored.<br />

Why a Parameterless Constructor<br />

If you think about it, you’ll realize why serialization has these restrictions. To serialize<br />

an object, the serializer must get an object’s property and field values. If a property or<br />

field is not public, the serializer cannot see it.<br />

When you deserialize an object, the serializer must create a new object and then set its<br />

values. If the class doesn’t have a parameterless constructor, it would need some way<br />

to figure out which constructor to use and what values to pass into it. You might cook<br />

up some scheme for telling it which constructor to use and how, but it would make<br />

deserialization more complicated. It’s just easier to require a parameterless constructor.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!