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 ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.