C# Binary Serialization

C# Code Snippets Binary Serialization
Share:

About

In this code snippet, we will learn about binary serialization in C#.

Serialization is when you take an object and convert it to a stream of bytes that can be then stored in a filedatabase or memory. This is useful if you want to store the state of your objects or send them over the network(for example an API). Of course, you can also deserialize a file/database entry back into an object. 

Note: See also how to do JSON or XML serialization.

In the code example, we will make a class and serialize it to a file using the BinaryFormatter. But to make the class serializable in the first place the ISerializable interface has to be implemented. To do that the GetObjectData method has to be defined and implemented.

Let’s have a look at the code below to see how to perform binary serialization.

Code:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialization
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of MyClass.
            MyClass MC = new MyClass(10, "I am just a a string.");

            //Serialize MC
            serialize(MC);

            //Deserialize MC from file to new obejct MCDeserialized.
            MyClass MCDeserialized = deserialize(MC);

            //Write out  MCDeserialized properties.
            Console.WriteLine("First property: " + MCDeserialized.MyFirstProperty + " Second property: " + MCDeserialized.MySecondProperty);

            Console.ReadLine();
        }

        public static void serialize(MyClass MC)
        {
            //Make file.
            Stream stream = File.Open("MyClassSerialized.obj", FileMode.Create);
            BinaryFormatter bfWrite = new BinaryFormatter();

            //Serialize the object data to a file.
            bfWrite.Serialize(stream, MC);
            stream.Close();
        }

        public static MyClass deserialize(MyClass MC)
        {
            //Open file.
            Stream streamRead = File.Open("MyClassSerialized.obj", FileMode.Open);
            BinaryFormatter bfRead = new BinaryFormatter();

            //Deserailze file back to object.
            MyClass MCDeserialized = (MyClass)bfRead.Deserialize(streamRead);

            streamRead.Close();

            return MCDeserialized;
        }
    }

    //Indicates that MyClass is serializable.
    [Serializable()]

    //We will use the ISerializable interface to make this class serializable.
    class MyClass : ISerializable
    {
        public int MyFirstProperty { get; set; }
        public string MySecondProperty { get; set; }

        //We will make this field unserializable.
        [NonSerialized()]
        public int MyNonSerializableFiled;

        //Just a standard constructor that initilaizes our class upon creation.
        public MyClass(int a, string b)
        {
            MyFirstProperty = a;
            MySecondProperty = b;
        }

        //GetObjectData is the method that will perform the seraialiazion. 
        //SerializationInfo will contain our data. In this case we won't be using SerializationContext. 
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            //Here we assign a key to our properties and add them to info. 
            info.AddValue("Prop1", MyFirstProperty);
            info.AddValue("Prop2", MySecondProperty);
        }

        //To deserialize data back to an object we will simnply create a constructor that takes in SerializationInfo info and StreamingContext ctxt.
        //Than we get the values from info an assign them back to our object's properties.

        public MyClass(SerializationInfo info, StreamingContext ctxt)
        {
            //Get the values from info and assign them to the properties
            MyFirstProperty = (int)info.GetValue("Prop1", typeof(int));
            MySecondProperty = (string)info.GetValue("Prop2", typeof(string));

        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger