Registration open for April 2018 batches of ASP.NET MVC and Design Patterns instructor-led online courses. Conducted by Bipin Joshi on weekends. Register today ! Click here for more details.

Serializing Objects using C#

Introduction

In simple words serialization is a
process of storing the object instance to a disk file. Serialization stores
state of the object i.e. member variable values to disk. Deserialization is reverse of
serialization i.e. it's a process of reading objects from a file where they have
been stored. In this code sample we will see how to serialize and deserialize
objects using C#.

public class ClassToSerialize{ public int age=100; public string name="bipin";

}

Explanation

Here we have our own class named ClassToSerialize. This
class has two public variables name and age with some default values. We will
write this class to a disk file (temp.dat) using SerializeTest class.

SerializeTest class has two methods SerializeNow() and
DeSerializeNow() which perform the task of serialization and deserialization
respectively.

The general steps for serializing are :

Create an instance of File that will store serialized
object

Create a stream from the file object

Create an instance of BinaryFormatter

Call serialize method of the instance passing it stream and object to
serialize

The steps for de-serializing the object are similar. The
only change is that you need to call deserialize method of
BinaryFormatter object.

Example 2

Now, let us see an example where we have
used 'real' class with public and shared members and properties to encapsulate
them. The class also uses another supporting class. This is just to make clear that if your
class contains further classes, all the classes in the chain will be
serialized.

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

Bipin Joshi is a software consultant, trainer, author and yoga mentor having 22+ years of experience in software development. He also conducts online courses on ASP.NET MVC, ASP.NET Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.