O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

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

3.33. Choosing a Serializer

Problem

The FCL contains several classes to allow objects to be serialized into different formats. Choosing the correct format for your task and remembering how to use that format can become a chore, especially when there is a mixture of different formats and all of them are on disk. You need some way of simplifying the serialization interfaces to make serialization easy without worrying about the underlying differences in the serialization classes. This will also allow other developers on your team to become proficient with the use of the various serializers more quickly.

Solution

Use the façade design pattern to create the following Serializer class:

using System; using System.Collections; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using System.Runtime.Serialization.Formatters.Soap; // Note that you must also add a reference to the following assembly: // System.Runtime.Serialization.Formatters.Soap.dll [Serializable] public class Serializer { public Serializer( ) {} protected Hashtable serializationMap = new Hashtable( ); protected Hashtable serializationTypeOfMap = new Hashtable( ); // Serialize an object public void SerializeObj(object obj, string destination) { SerializeObj(obj, destination, SerializationAction.Default); } public void SerializeObj( object obj, string destination, SerializationAction action) { if (action == SerializationAction.RetainAssemblyInfo || action == SerializationAction.RetainPrivateMembers ...

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