□ Private variables and properties are all serialized. In binary serialization, both the private variables and properties are serialized. This is known as
□ Object graphs are serialized and preserved. In this example, two BookMark
objects are linked, and the serialization process takes care of the relationships between the two objects.
There are times when you do not want to serialize all of the data in your object. If you don't want to persist the date and time that the BookMark
objects are created, for instance, you can prefix the variable name (that you do not want to serialize) with the [NonSerialized]
attribute:
[Serializable]
class BookMark {
private DateTime _dateCreated;
public BookMark() {
_dateCreated = DateTime.Now;
}
public DateTime GetDateCreated() {
return _dateCreated;
}
public string URL { get; set; }
public string Description { get; set; }
public BookMark NextURL { get; set; }
}
The dateCreated
variable will not be serialized. Figure 11-14 shows that when the dateCreated
variable is not serialized, its value is set to the default date when the object is deserialized.

Figure 11-14
XML Serialization
You can also serialize an object into an XML document. There are many advantages to XML serialization. For instance, XML documents are platform-agnostic because they are in plain text format and that makes cross- platform communication quite easy. XML documents are also easy to read and modify, which makes XML a very flexible format for data representation.
The following example illustrates XML serialization and shows you some of its uses.
Let's define a class so that you can see how XML serialization works. For this example, you define three classes that allow you to store information about a person, such as name, address, and date of birth. Here are the class definitions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Serialization {
class Program {
static void Main(string[] args) { }
}
}
The various classes are deliberately designed to illustrate the various aspects of XML serialization. They may not adhere to the best practices for defining classes.
Here are the specifics for the classes:
□ The Member
class contains both private and public members. It also contains a read-only property.
□ The Member
class contains a public array containing the address of a Member.
□ The Member
class contains a variable of Date
data type.
□ The MemberName
class contains two properties.
□ The MemberAddress
class contains only public members.
To serialize a Member
object into a XML document, you can use the