Object Serialization in .Net, BinaryFormatter Serialization, SoapFormatter Serialization, XmlSerializer in C#

Serialization means saving the state of an object in stream of bytes. Saved information contains all the data to reconstruct the object by using deserialization.

 

Serialization is very useful in many situations while developing any application, mainly the distributed application. Basically sender sends the information receiver; until sender receives the acknowledgement from receiver sender has to save that information.  If you are sending several properties to receiver, capturing the each property individually very difficult. Instead of saving each property individually, make one class and add all properties, variables to that class which are sending to receiver. Then create object to that class and save that object by using serialization.

 

There are three types of Serialization in .Net. Those are BinaryFormatter,SoapFormatter,  XmlSerializer. We discuss about each one here.

 

You can make any class serializable by using “Serializable” keyword as shown below.

 

[Serializable]

public class Employee

{

        public int id;

        private string location = "ABC";

        public string Location

        {

            get { return location; }

            set { location = value; }

        }

}

 

If you make the class serializable, then all properties and variables are also serializable. If you don’t want to make any property or variable as serailizable, then apply NonSerialized as shown below.

 

[Serializable]

public class Employee

{

        public int id;


        [NonSerialized]

        public string name;

 

        private string location = "ABC";

        public string Location

        {

            get { return location; }

            set { location = value; }

        }

}

 

But NonSerialized will not work if you are using XmlSerializer formatter.

Each formatter uses Serialize() method for seralization and Deserialize method for deserialization.

 

To explain each formatter use the Employee class which has some private variables, properties and class is serializable as shown below.

 

using System;

namespace SerializationExample

{

    [Serializable]

    public class Employee

    {

        public int id;

        public string name;

        private double sal = 10000; // it is not serialized in XML formatter

 

       

        private string location = "ABC";

        public string Location

        {

            get { return location; }

            set { location = value; }

        }

    }

}

 

Binary Formatter Serialization and DeSerialization:

In this serialization, object converts into stream of bytes.  It allows all variables and properties for serialization irrespective of whether it is private, public, protected…etc.

 

Create common class to hold methods for Binary Formatter serialization and deserialization as shown below. Import System.Runtime.Serialization.Formatters.Binary namespace in class to make available the Serialize() and Deserialize() methods.

 

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;


namespace SerializationExample

{

    class BinaryFormatterExp

    {

        public static void BinarySerialization(object obj)

        {

            BinaryFormatter binaryFormat = new BinaryFormatter();

            using (Stream fStream = new FileStream("C:\\BinarySerialization.txt", FileMode.Create, FileAccess.Write, FileShare.None))

            {

                binaryFormat.Serialize(fStream, obj);

            }

        }

 

        public static object BinaryDeSerialization()

        {

            BinaryFormatter binaryFormat = new BinaryFormatter();

 

            Stream fStream = File.OpenRead("C:\\BinarySerialization.txt");

 

            Employee objEmp = (Employee)binaryFormat.Deserialize(fStream);

 

            return objEmp;

        }

   }

}

 

Here state of object is converted into binary format and save in some text file BinarySerialization.txt using Serialize method. For deserialization, get the binary information from BinarySerialization.txt file and get the state of object by using Deserialize() method.

 

SoapFormatter Serialization and DeSerialization:

SoapFormatter Serialization also same as BinaryFormatter serialization, but for SoapFormatter serialization you need to add reference for System.Runtime.Serialization.Formatters.Soap.dll assembly by selecting “Add Reference” from solution explorer. SoapFormatter also serialize all properties and variables irrespective their scope.

 

Create common class to hold methods for Soap Formatter serialization and deserialization as shown below. Import System.Runtime.Serialization.Formatters.Soap namespace in class to make available the Serialize() and Deserialize() methods.

 

using System.IO;

using System.Runtime.Serialization.Formatters.Soap;

 

namespace SerializationExample

{

    class SOAPFormatterExp

    {

        public static void SOAPSerialization(object obj)

        {

            SoapFormatter soapFormat = new SoapFormatter();

            using (Stream fStream = new FileStream("C:\\SOAPSerialization.txt", FileMode.Create, FileAccess.Write, FileShare.None))

            {

                soapFormat.Serialize(fStream, obj);

            }

        }


        public static object SOAPDeSerialization()

        {

            SoapFormatter soapFormat = new SoapFormatter();

 

            Stream fStream = File.OpenRead("C:\\SOAPSerialization.txt");

 

            Employee objEmp = (Employee)soapFormat.Deserialize(fStream);

  

            return objEmp;

        }

    }

}

 

Here state of object is converted into soap format and save in some text file SOAPSerialization.txt using Serialize method. For deserialization, get the soap information from SOAPSerialization.txt file and get the state of object by using Deserialize() method.

 

XmlSerializer and Deserialization:

XmlSerializer saves the state of object in XML format. That means class name behaves like a parent element and all its properties, variables …etc behave like child elements. You can serialize all its public variables, properties. But you cannot serialize private members by using XML Serializer. If you want to XML serialize private members, add public property and assign private variable to that public property.

 

Create common class to hold methods for XmlSerializer serialization and deserialization as shown below. Import System.Xml.Serialization namespace in class to make available the Serialize() and Deserialize() methods.

 

using System.IO;

using System.Xml.Serialization;

 

namespace SerializationExample

{

    class XmlSerializerExp

    {

        public static void XMLSerialization(object obj)

        {

            XmlSerializer xmlFormat = new XmlSerializer(typeof(Employee));

            using (Stream fStream = new FileStream("C:\\XMLSerialization.xml", FileMode.Create, FileAccess.Write, FileShare.None))

            {

                xmlFormat.Serialize(fStream, obj);

            }

        }

 

        public static object XMLDeSerialization()

        {

            XmlSerializer xmlFormat = new XmlSerializer(typeof(Employee));

 

            Stream fStream = File.OpenRead("C:\\XMLSerialization.xml");

 

            Employee objEmp = (Employee)xmlFormat.Deserialize(fStream);

 

            return objEmp;

        }

    }

}

 

Here state of object is converted into XML format and save in some text file XMLSerialization.xml using Serialize method. For deserialization, get the XML information from XMLSerialization.xml file and get the state of object by using Deserialize() method.

 

Now create object for Employee class and pass to each formatter for serialization based on selection as shown below.

 

private void btn1_Click(object sender, EventArgs e)//For Serialization

{

            Employee objEmp = new Employee();

            objEmp.id = 1;

            objEmp.name = "Bob";

 

            if (comboBox1.SelectedIndex == -1)

            {

                MessageBox.Show("Please Select Formatter for Serialization");

                comboBox1.Focus();

                return;

            }

            else if (comboBox1.SelectedIndex == 0)

                BinaryFormatterExp.BinarySerialization(objEmp);

            else if (comboBox1.SelectedIndex == 1)

                SOAPFormatterExp.SOAPSerialization(objEmp);

            else if (comboBox1.SelectedIndex == 2)

                XmlSerializerExp.XMLSerialization(objEmp);

 

            MessageBox.Show(comboBox1.Text + " Serialization is done");

}

 

private void btn2_Click(object sender, EventArgs e)//for deserialization

{

            try

            {

                Employee objEmp;

                if (comboBox1.SelectedIndex == -1)

                {

                    MessageBox.Show("Please Select Formatter for DeSerialization");

                    comboBox1.Focus();

                    return;

                }

                else if (comboBox1.SelectedIndex == 0)

                {

                    objEmp = (Employee)BinaryFormatterExp.BinaryDeSerialization();

                }

                else if (comboBox1.SelectedIndex == 1)

                {

                    objEmp = (Employee)SOAPFormatterExp.SOAPDeSerialization();

                }

                else

                {

                    objEmp = (Employee)XmlSerializerExp.XMLDeSerialization();

                }

 

                string str = comboBox1.Text + " DeSerialization is done and data is \n\n";

                str = str + " Id: " + objEmp.id.ToString() + "\n";

                str = str + " Name: " + objEmp.name.ToString() + "\n";

                str = str + " Location: " + objEmp.Location.ToString() + "\n";

 

                MessageBox.Show(str);

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message + "\n\n" + "Do the " + comboBox1.Text + " Serialization first");

            }

}

 

Here we have drop down list which contains all three Binary Formatter, Soap Formatter, XML Serailizer options and two buttons, one is for serialization and other is for deserialization.

 

Output after saving the object state using Binary Formatter look like below.

 

 

Output after saving the object state using Soap Formatter look like below.

 

 

Output after saving the object state using XML Serializer look like below.

 

                                                                                                    SerializationExample.zip (49.88 kb)