Home > Basics > Simple C# Serialization

Simple C# Serialization

(Kudos if you noticed the alliterated title)
(Edit: this is an old article I never published. Until now! I hope it serves as a nice introduction to beginners).

Serialization is a thing I had (until recently) left untouched. For too long. Well, no more. Here are the basics.

What is serialization?
Simply put, it’s taking an object’s value(s) and writing them to a file (or a buffer, but I’m not covering that here) for transmission or storage.

What is deserialization?
It’s the reverse, building an object from a file (or buffer).

Why serialize?
Serialization can be used for various reasons, such as transmitting data to another computer or storing it. Storage could potentially be done with a database, but even something portable like SQLite is another thing to maintain, whereas for minimal needs, serialization offers quick and dirty clean storage for later use. For example, I’m using it for storing a few sets of parameters for batch processing.

Here’s how. I will be using the simplest form of XML serialization (that is, writing to, and naturally reading from XML), not Soap, but with the very vanilla System.Xml.Serialization namespace.

First, add System.Xml to your project’s references.

Now, we’ll design the basic class we want to serialize. First, the class without the serialization attributes:

public class ClientInfo
{
    public string ClientName { get; set; }
    public int ClientId { get; set; }
    public DateTime ProcessTime { get; set; }

    public ClientInfo (string clientName, int clientId)
    {
        ClientName = clientName;
        ClientId = clientId;
    }
}

To serialize, first we’ll need the proper namespace, so add:

using System.Xml.Serialization;

in your using block at the top.

Next, we’ll decide what we want to serialize. Let’s say ClientName and ClientId, but ProcessTime shouldn’t be serialized at all (for some reason. Hey, I just needed the example).

So, we’ll need to tell the compiler that the class is serializable, simply by adding the attribute above the class declaration:

[Serializable]
public class ClientInfo
{/...

By default, all fields become serializable. Let’s specify the field to ignore appropriately:

    public string ClientName { get; set; }
    public int ClientId { get; set; }
    [XmlIgnore] //Tells C# to forget about that value for serialization
    public DateTime ProcessTime { get; set; }

Serialization also requires a default constructor. And the nice thing is that it does not have to be public, so your class logic can remain the same from outside (i.e. no default instantiation if you don’t want it):

    private ClientInfo()
    { }

The total result:

using System.Xml.Serialization;

[Serializable]
public class ClientInfo
{
    public string ClientName { get; set; }
    public int ClientId { get; set; }
    [XmlIgnore]
    public DateTime ProcessTime { get; set; }

    public ClientInfo (string clientName, int clientId)
    {
        ClientName = clientName;
        ClientId = clientId;
    }

    private ClientInfo()
    { }
}

And we’re done for that part! Now, suppose you want to serialize that into an Xml file. Use a function like so:

public static bool SaveConfig(ClientInfo clientInfo, string filePath)
{
    FileStream flStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); 
    //do add proper handling of possible stream exceptions here
    bool success = false;
    try
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(List));
        xmlSerializer.Serialize(flStream, clientInfo);
        success = true;
    }
    finally
    {
        flStream.Close();
    }
    return success;
}

And reading, essentially taking the XML class and making it into an object is just as easy, it’s called
deserialization:

public ClientInfo LoadConfig(string filePath)
{
    if (!File.Exists(filePath))
        return null; //Or ClientInfo.Default if you made one
    
    ClientInfo clientInfo = null;
    FileStream flStream = new FileStream(destFileName, FileMode.Open, FileAccess.Read);
    //do add proper handling of possible stream exceptions here
    try
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(ClientInfo));
        clientInfo = xmlSerializer.Deserialize(flStream) as ClientInfo;
    }
    finally
    {
        flStream.Close();
    }
    return clientInfo;
}

This is just the tip of the iceberg. You can serialize/deserialize sub-objects, collections, etc. This is very useful for reading and writing back. And of course if you need to serialize/deserialize something large, there are better ways, like binary serialization!

About these ads
Categories: Basics Tags:
  1. 2012-06-23 at 2:59 pm | #1

    I enjoyed your insightful writing. brilliant work. I hope you write more. I will carry on subscribing

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: