Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Tuesday, April 8, 2008

What attribute should you add to a class to allow it to be serialized?

A class can be serialized when it has the "Serializable" attribute. Serialization is the process of storing the contents of an object to long term storage. If you will only be using .NET Framework based applications to process your serialized objects, then the BinaryFormatter class will be the most efficient. If you will be transmitting your serialized object across a network or sharing it with a non .NET Application, then the SoapFormatter class should be used to export the object to the XML based SOAP format.

Serialization Example
Note that you need to add a reference to System.Runtime.Serialization.Formatters.Soap.dll to your project before compiling the code below. Unlike the BinaryFormatter class, the SoapFormatter class is not included by default.


using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

namespace SerializationExample
{
[Serializable]
class ObjectToSerialize
{
string sName;
int iCount;
double dPrice;

public ObjectToSerialize(string newName, int newCount, double newPrice)
{
sName = newName;
iCount = newCount;
dPrice = newPrice;
}
}

class Program
{
static void Main(string[] args)
{
ObjectToSerialize o = new ObjectToSerialize("Video Game", 1, 50.00);

// Create the files to save the data to
FileStream binary_fs = new FileStream("Serialization_Example.bin", FileMode.Create);
FileStream xml_fs = new FileStream("Serialization_Example.xml", FileMode.Create);

// Create a BinaryFormatter object to perform the serialization
BinaryFormatter bf = new BinaryFormatter();
// Create a SoapFormatter object to perform serialization
SoapFormatter sf = new SoapFormatter();

// Use the BinaryFormatter object to serialize the data to the file
bf.Serialize(binary_fs, o);
// Use the SoapFormatter object to serialize the data to the file
sf.Serialize(xml_fs, o);

// Close the files
binary_fs.Close();
xml_fs.Close();
}
}
}


Binary Results
SOAP Results
The XML results of the SOAP Serialization can be found here: SOAP Serialization Results

Additional Resources
BinaryFormatter Class (Microsoft)
SoapFormatter Class (Microsoft)

No comments:

Support This Site

LinkShare  Referral  Prg