Serialization

Binary Serialization with C# and .NET

Posted on Updated on

In the previous post, we discussed XML serialization. In this short article we are going to take a look at binary serialization via the BinaryFormatter class. As we mentioned in a previous article, binary serialization in .NET converts an object or entire object graph into a binary format that is not human readable. Binary serialization is sometimes called “deep” serialization because it serializes the entire object state, all relations among an object graph, and all references to other objects. It preserves type fidelity which is quite useful when utilizing objects across multiple applications of instances of the same application.

Binary Serialization with the BinaryFormatter class

To get started, let’s create a simple class, add some attributes to help us control how properties are serialized, then we’ll serialize and deserialize the object.

To get started, let’s create a C# Console Application that we will call BinarySerializationSample.

Create Binary Serialization Sample Application
Create Binary Serialization Sample Application

Next, we will add a class to the project. We will call this class Sample.

Let’s now add two properties – Name and Value as shown below then decorate the class with the Serializable attribute.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerializationSample
{
    [Serializable]
    public class Sample
    {
        public string Name
        {
            get;
            set;
        }

        public Int32 Value
        {
            get;
            set;
        }
    }
}

Before we can use binary serialization, we have to add a reference to the System.Runtime.Serialization assembly. Right-click the project, select Add Reference, then select this assembly in the dialog. See below.

System.Runtime.Serialization Assembly Reference
System.Runtime.Serialization Assembly Reference

Now that we have created our Sample class, decorated it with the Serializable attribute, and added a reference to the System.Runtime.Serialization assembly, let’s jump to our Program class’s Main() method and write some simple code to serialize an instance of our object. The full code for our Program class is shown below.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace BinarySerializationSample
{
    class Program
    {
        static void Main(string[] args)
        {
            //create an instance of our Sample object
            Sample sample = new Sample();
            sample.Name = "John Nelson";
            sample.Value = 44;

            //create a FileStream to write the serialized output
            //to a file on our hard drive
            FileStream fileStream = new FileStream(@"c:\Temp\Sample.dat", FileMode.Create);

            //create a BinaryFormatter object to serialize our object
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fileStream, sample);

        }
    }
}

Now let’s press F5 and run our console application. We will open the file with Wordpad so that the text wraps and so that we can see the contents. See below.

Output of Binary Serialization
Output of Binary Serialization

The binary output does have some readable text. The first thing you should notice is that the entire assembly and namespace information is stored with the serialized object. This is something that XML serialization does NOT do. Pretty cool.

Be sure not to save the file because we are going to use this same file in the code below to deserialize our object.

//create a FileStream to read the serialized object
FileStream fileStream = new FileStream(@"c:\Temp\Sample.dat", FileMode.Open);

//create a BinaryFormatter and deserialize the object
BinaryFormatter formatter = new BinaryFormatter();
Sample deserializedSample = (Sample)formatter.Deserialize(fileStream);

Console.WriteLine("The deserialized object:");
Console.WriteLine(String.Format("Name: {0}", deserializedSample.Name));
Console.WriteLine(String.Format("Value: {0}", deserializedSample.Value.ToString()));

Console.Read();

When we press F5 and run our application, we see the following output in our console window:

Binary Deserialization Output
Binary Deserialization Output

Pretty cool, right? Yes it is.

Now this was a very simple example but understand that any object that supports serialization can be serialized using the BinaryFormatter. If we have an object graph that contained multiple levels of objects in a hierarchy, we could serialize these objects in exactly the same way that we just did. I have written numerous applications that have required objects to be serialized and stored in a database. Again, we use the same approach, then we execute a stored procedure or invoke an insert or update call and pass the binary data into the table. No big deal.

In the next post, we will take a look at SOAP Serialization with C# and .NET.

Serialization with C# and .NET

Posted on Updated on

What is Serialization?

In the world of software development, serialization is the process of converting an object into a format that allows it to either be persisted (saved) to disk or memory, or to be transmitted across a network or over HTTP or TCP.

An object that has been serialized can be reconstructed later which is known as deserialization. I like to think of deserialization as the process by which we re-inflate the object back into its original state. If you think of an XML web service as an example, an application can be written using standard .NET objects, serialized as XML, passed around via HTTP or TCP, then deserialized (re-inflated) by the receiving application and used further.

In this article, we are going to take a quick look at three forms of .NET serialization and talk briefly about each. The following three articles will address XML serialization, binary serialization, and SOAP serialization and provide walkthroughs that give you an overview of how to implement each.

Serialization in .NET

The .NET Framework provides a few serialization mechanisms. Let’s discuss the three most well-known:

  • XML Serialization – serializes the public fields and properties of an object into an XML stream. XML serialization does not record or preserve information about the object’s original type or namespace. The .NET Framework provides a class called the XmlSerializer. This class provides methods with which we can serialize an deserialize objects.
  • Binary Serialization – serializes an object or an entire hierarchy of objects into a binary format. Binary serialization is a very efficient means of serializing .NET objects. The BinaryFormatter class offers numerous methods allow us to serialize and deserialize objects.
  • SOAP Serialization – serializes an object into XML, but also serializes private members. SOAP serialization does not support serialization of generic collections, but the SoapFormatter saves assembly and type information along with the data itself. SOAP serialization is ideal for communications between heterogeneous applications, or applications that are written using different architectures, languages, platforms, etc.

The decision as to which type to use is dictated by the needs of the application. For example, XML and SOAP serialization produce XML output which is usable across multiple platforms. Binary serialization in .NET should only be used in situations where the objects to be serialized and deserialized reside in namespaces that are usable and referenced by each application. If there is only one application in the discussion, then binary serialization will provide a speedy, compact form of serialization that will be quite suitable. So it comes down to considering performance, storage type and location, and extensibility.

See the table below for a high-level comparison of these three types of .NET serialization.

Comparison of XML Serialization, SOAP Serialization, and Binary Serialization
Comparison of XML Serialization, SOAP Serialization, and Binary Serialization

To use serialization in .NET, you essentially only need two things:

  1. A stream to hold or receive the serialized output
  2. A formatter (XmlSerializer, SoapFormatter, or BinaryFormatter) to fill the stream with output

As we mentioned earlier, XML Serialization utilizes the XmlSerializer class, binary serialization is provided via the BinaryFormatter, and SOAP serialization is handled by the SoapFormatter – .NET provides very rich support for serialization.

.NET Serialization Walkthroughs

The following posts will dive into the specifics of serialization with C# and .NET. Use the links below to select the appropriate post.

XML Serialization in C# and .NET

Binary Serialization in C# and .NET

SOAP Serialization in C# and .NET