Binary Serialization
Consider the following class, BookMark
, which is used to stored information about web addresses and their descriptions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Serialization {
class Program {
static void Main(string[] args) {}
}
}
The BookMark
class contains properties as well as private variables. The NextURL
property links multiple BookMark
objects, much like a linked list. Let's now create two BookMark
objects and link them:
static void Main(string[] args) {
}
You can serialize the objects into a binary stream by writing the Serialize() function:
static void Main(string[] args) {
//...
}
For binary serialization, you need to import the System.Runtime.Serialization.Formatters.Binary
namespace.
The Serialize()
function takes in a single parameter (the BookMark
object to serialize) and returns a MemoryStream
object representing the serialized BookMark
object. You use the BinaryFormatter
class from the System.Runtime.Serialization.Formatters.Binary
namespace to serialize an object. One side effect of this function is that it also serializes the BookMark
object to file, using the FileStream
class.
Before you serialize an object, you need to prefix the class that you want to serialize name with the [Serializable]
attribute:
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 following statement serializes the bm1 BookMark
object, using the Serialize ()
function:
static void Main(string[] args) {
BookMark bm1, bm2;
bm1 = new BookMark {
URL = 'http://www.amazon.com',
Description = 'Amazon.com Web site'
};
bm2 = new BookMark() {
URL = 'http://www.wrox.com',