Click here to Skip to main content
Click here to Skip to main content

Serializing with .NET 2.0 Generics

, 23 May 2006
Rate this:
Please Sign up or sign in to vote.
A simple base class to add serialization support to your data classes.

Introduction

On a project I was working on, we were in the need for serialization en mass. A lot of classes had to be serializable. Following are the requirements, the stages towards a solution, and a proposed solution.

Design goals:

  • It must be simple for the application programmer.
  • The serialization output should be XML.
  • Future changes in the serialization code must not involve making changes to the client code. E.g., we may have to encrypt the serialized object representation.

Using the code

Since this was my first date with serialization, I naturally went Googling to get a feeling for who I'm dating. It quickly seemed that serialization wasn't that hard. Many people suggested using the following wherever you need to serialize:

Dim serializedObj As String
Dim serializer As New XmlSerializer(Me.GetType)
Dim writer As New StringWriter
serializer.Serialize(writer, Me)
serializedObj = writer.ToString()

Not so bad. You decorate your class with the <SERIALIZABLE()> attribute, and maybe hide a few public properties with XmlIgnore, and there you go. It was immediately ruled out to have the client code contain this code in every class. So what about a utility method that will serialize/deserialize an object? There are a few challenges here. The utility function must be able to handle any type of object. Until .NET 2.0, the answer would probably have been something along these lines:

Public Shared Function Serialize(obj as Object) As String

That looks OK. Let's have a look at the Deserialize method as well, and see if there are any surprises hiding there. In order to deserialize, we need another piece of information that we had when serializing. We need to know what type to deserialize to. The following signature should give us enough information to get the job done.

Public Shared Function Deserialize(xml As String, _
                       obj As Object) As Object

The client code would then look something like:

' serialize
Dim instance1 As New TestClass
Dim serializedInstance As String = _
    SharedLib.Serialize(instance1)

' deserialize
Dim instance2 As New TestClass
instance2 = CType(SharedLib.DeSerialize(serializedInstance, _
                  instance2), TestClass)

At this point, I was in doubt. Should I stop here and accept something that I didn't feel very good about, or should I spend some more time to try to find a better solution? I had two problems with the above code. The client code was not intuitive enough, and there was still too much code needed to get the job done. From an object oriented perspective, I would much more like to have the methods on the class itself. I decided to look for something else. I hear you shout Generics, so here it comes, but with a twist. We'll leave the concept of utility functions all together. In a normal object model, you have objects that contain state and do actions. Most of us don't write helperLib.Drive(myCar), but rather myCar.Drive(). How can we apply that to the serialization problem at hand?

Let's first look at how we want the calling code to look like, and then on how to implement our serialization to match that.

' serialize
Dim instance1 As New TestClass
Dim serializedInstance As String = instance1.Serialize()

' deserialize
Dim instance2 As TestClass1
instance2 = TestClass1.Deserialize(serializedInstance)

That's what I want the calling code to look like. Just to make things even between VB.NET and C#, I'll do the remaining part in C#. We want to add a Serialize() and a Deserialize() method to any class that needs to be serialized. In order to minimize the coding effort of the classes that will use this functionality in, we will write a generic base class with the implementation of the two methods.

Here is the base class implementation:

[Serializable()]
public abstract class ContractBase<T>
{

  /// Must have default constructor for xml serialization
  public ContractBase()
  {
  }

  /// Create an xml representation of this instance
  public string Serialize()
  {
     XmlSerializer serializer = new XmlSerializer(this.GetType());
     using (StringWriter stream = new StringWriter())
     {
        serializer.Serialize(stream, this);
        stream.Flush();
        return stream.ToString();
     }
  }

  /// Creata a new instance from an xml string.
  /// The client is responsible for deserialization of the correct type
  public static T Deserialize(string xml) 
  {
     if (string.IsNullOrEmpty(xml))
     {
        throw new ArgumentNullException("xml");
     }

     XmlSerializer serializer = new XmlSerializer(typeof(T));
     using (StringReader stream = new StringReader(xml))
     {
        try
        {
           return (T)serializer.Deserialize(stream);
        }
        catch (Exception ex)
        {
           // The serialization error messages are cryptic at best.
           // Give a hint at what happened
           throw new InvalidOperationException("Failed to " + 
                            "create object from xml string", ex);
        }
     }
  }
}

Here is a sample class, using the serialization base class we just wrote:

[Serializable()]
public class TestClass : ContractBase< TestClass >
{
  private string m_firstName;
  public string FirstName
  {
     get
     {
        return m_firstName;
     }
     set
     {
        if (m_firstName == value)
           return;
        m_firstName = value;
     }
  }

Note that the TestClass inherits from a generic base class, passing in its own type as the generic type.

The calling code now looks like what we wanted.

//serialize
TestClass instance1 = new TestClass();
string serializedInstance = instance1.Serialize();

//deserialize
TestClass instance2;
instance2 = TestClass.Deserialize(serializedInstance);

See a better solution? Please let me know.

You can also visit my blog.

History

  • First revision.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Kim Major
Web Developer
Israel Israel
No Biography provided

Comments and Discussions

 
Generalstyle Pinmemberbryce22-Apr-09 16:45 
Generalthanks a lot Pinmemberalmanzora200026-Jan-07 18:05 
GeneralXmlSerializer short-comings PinmemberOrium112-Oct-06 10:52 
GeneralRe: XmlSerializer short-comings PinmemberKim Major2-Oct-06 11:48 
Generalvb conversion Pinmemberconstantnet21-Sep-06 9:41 
GeneralRe: vb conversion [modified] PinmemberKim Major21-Sep-06 22:50 
GeneralWell writen Pinmemberdmeccl8-Jun-06 23:20 
GeneralNicely done PinmemberT-luv27-May-06 8:57 
GeneralRe: Nicely done PinmemberKim Major27-May-06 23:26 
GeneralSerializer and Deserializer to file PinmemberTHMok23-May-06 17:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 23 May 2006
Article Copyright 2006 by Kim Major
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid