Click here to Skip to main content
11,920,641 members (59,068 online)
Click here to Skip to main content
Add your own
alternative version


299 bookmarked

Object Serialization using C#

, 31 Jan 2002
Rate this:
Please Sign up or sign in to vote.
How to serialize custom created class objects using C#
<!-- Download Links --> <!-- Add the rest of your HTML here -->


Writing crucial data to the disk as TEXT is always dangerous. Any anonymous user can open the text file and easily read your data. With Object Serialization, you can reduce this danger to a certain extent. You can write any complex object directly to a filestream without converting values of individual properties into a text. You can make the data written, to the disk, atleast not human readable. In order for the users to read your data files, they have to use your program. Like a File Open command which you may provide in your application.

.NET and Object Serialization

Now what does .NET framework provide us to do Serialization of Custom-build class objects? With the advent of any programming language, developers would first look whether it is an OOPL. If so, how to create my own classes with my own properties and functions. And then comes inheritance and all others. Explaining how to create user-defined classes is out of scope of this article. But along the way you will get to know about what a user-defined class is.

Serialization explained

Serialization is the process of converting complex objects into stream of bytes for storage. Deserialization is its reverse process, that is unpacking stream of bytes to their original form. The namespace which is used to read and write files is System.IO. For Serialization we are going to look at the System.Runtime.Serialization namespace. The ISerializable interface allows you to make any class Serializable.

Here are the following steps that we are going to do to create a serializable class and test it.

  • Create a custom class named Employee and assign properties.
  • Define the serialization functions.
  • Create a main class and instantiate our Employee class.
  • Serialize the object to a sample file.
  • Deserialize the values by reading it from the file.

Defining Employee class and properties

Our custom class Employee should be derived from the ISerializable interface and should hold the Serializable attribute. Here is the code snippet.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace MyObjSerial
    [Serializable()]    //Set this attribute to all the classes that want to serialize
    public class Employee : ISerializable //derive your class from ISerializable
        public int EmpId;
        public string EmpName;
        //Default constructor
        public Employee()
            EmpId = 0;
            EmpName = null;

Define Serialization functions

Now we need two functions: One to say how to serialize Employee objects and another to say how to deserialize them. For serialization we override the GetObjectData() function provided by the ISerializable interface. For deserialization we provide a special constructor with the serialization parameters as arguments. This constructor will be called when we deserialize our file to object (which will be shown later).

One of the important parameters is the SerializationInfo object. This object holds a name-value pair for the properties to be serialized. You can decide which property should be serialized and which not in the GetObjectData() function. All the properties that are added to this SerializationInfo parameter will be serialized. Here are the codes for the two functions. Add them to our Employee class.

//Deserialization constructor.
public Employee(SerializationInfo info, StreamingContext ctxt)
    //Get the values from info and assign them to the appropriate properties
    EmpId = (int)info.GetValue("EmployeeId", typeof(int));
    EmpName = (String)info.GetValue("EmployeeName", typeof(string));
//Serialization function.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    //You can use any custom name for your name-value pair. But make sure you
    // read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
    // then you should read the same with "EmployeeId"
    info.AddValue("EmployeeId", EmpId);
    info.AddValue("EmployeeName", EmpName);
Thats it. You have created your own class which is now serializable. Now lets see how to write an instance of Employee to a special file with a custom .osl extension. And we also see how to read back Employee object from the file.

Create a main class and instantiate our Employee class

Following is the code snippet for ObjSerial class which holds our application's main entry point.
//Main class
public class ObjSerial
    public static void Main(String[] args)
        //Create a new Employee object
        Employee mp = new Employee();
        mp.EmpId = 10;
        mp.EmpName = "Omkumar";
        //Add code below for serialization

Serialize the object to a sample file

For serializing, lets open a stream object and give a sample file name EmployeeInfo.osl. Note, the demo exe file has this same name. So when you run ObjSerial.exe, the EmployeeInfo.osl file will be created under the folder where you copied the exe file. Add the following code to our ObjSerial class. Once a stream is open we create a BinaryFormatter and use the Serialize method to serialize our object to the stream. What Serialize method would do? It converts our object into binary format and streams it in.
// Open a file and serialize the object into it in binary format.
// EmployeeInfo.osl is the file that we are creating. 
// Note:- you can give any extension you want for your file
// If you use custom extensions, then the user will now 
//   that the file is associated with your program.
Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream, mp);

Deserialize the values by reading it from the file

Now we read the created file and cast the return value to our Employee class for further usage. For reading we again create a BinaryFormatter to read the object in binary form. We then use the Deserialize method which converts the stream of bytes to an Object object. This object can then be easily casted to our Employee class.
//Clear mp for further usage.
mp = null;
//Open the file written above and read values from it.
stream = File.Open("EmployeeInfo.osl", FileMode.Open);
bformatter = new BinaryFormatter();
Console.WriteLine("Reading Employee Information");
mp = (Employee)bformatter.Deserialize(stream);
Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name: {0}",mp.EmpName);


This sample application explains the core part of serialization only. Actually you can do a lot with the objects while serializing and deserializing. Now you can create a Mulitple document application with .NET Windows Forms and go ahead Serialize the world into your disk.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Web Developer
United States United States
Started programming with computers in 1995. Ever since it keeps me busy and creative. Did a bachelor's degree in electronics and communication only to better understand the inside of computers and its power. Currently working as a software developer in US and looking for a girl-friend...

You may also be interested in...

Comments and Discussions

QuestionIt's easier to serialise now Pin
Member 982271420-Jun-15 11:32
memberMember 982271420-Jun-15 11:32 
GeneralMy vote of 5 Pin
lvganesh849-May-15 8:57
memberlvganesh849-May-15 8:57 
QuestionC# Serialization Pin
Linojan20-Apr-15 1:18
memberLinojan20-Apr-15 1:18 
GeneralA nice one Pin
Arkadeep De2-Nov-14 8:03
professionalArkadeep De2-Nov-14 8:03 
QuestionMy vote of 5 Pin
GuyThiebaut1-Nov-14 23:44
memberGuyThiebaut1-Nov-14 23:44 
Questionusing stream Pin
Dietmar Schoder10-Dec-13 23:57
professionalDietmar Schoder10-Dec-13 23:57 
GeneralMy vote of 5 Pin
naren19915-Jun-13 22:29
membernaren19915-Jun-13 22:29 
GeneralMy vote of 5 Pin
manoj kumar choubey25-Apr-13 2:22
membermanoj kumar choubey25-Apr-13 2:22 
QuestionCare with ENUM types Pin
Oscar Miras29-Nov-12 3:13
memberOscar Miras29-Nov-12 3:13 
QuestionDeserialize Pin
ingvare14-Nov-12 3:18
memberingvare14-Nov-12 3:18 
GeneralMy vote of 5 Pin
Tem Rhythm11-Sep-12 22:52
memberTem Rhythm11-Sep-12 22:52 
Questionserialization Pin
jingdedi22-Aug-12 0:07
memberjingdedi22-Aug-12 0:07 
GeneralMy vote of 5 Pin
Akiii0018-Jun-12 6:08
memberAkiii0018-Jun-12 6:08 
Suggestion[My vote of 2] My vote of 2 - dangerous Pin
andyclap23-Jan-12 1:20
memberandyclap23-Jan-12 1:20 
GeneralMy vote of 5 Pin
Sergiy Tkachuk15-Dec-11 20:21
memberSergiy Tkachuk15-Dec-11 20:21 
QuestionData is readable Pin
S.Reda30-Jun-11 2:55
memberS.Reda30-Jun-11 2:55 
GeneralMy vote of 4 Pin
shankaranarayana18-May-11 1:14
membershankaranarayana18-May-11 1:14 
GeneralAnother great site with info on serialization Pin
jonarnar24-Apr-11 3:51
memberjonarnar24-Apr-11 3:51 
QuestionHow to De-serialize whole array or list of ojbects Pin
Mushtaq Muhammad3-Apr-11 1:06
memberMushtaq Muhammad3-Apr-11 1:06 
AnswerRe: How to De-serialize whole array or list of ojbects Pin
jonarnar24-Apr-11 3:52
memberjonarnar24-Apr-11 3:52 
QuestionGreat, exactly what I needed though I have a small question Pin
IlanF25-Mar-11 2:29
memberIlanF25-Mar-11 2:29 
GeneralMy vote of 4 Pin
dendrit6-Dec-10 2:15
memberdendrit6-Dec-10 2:15 
although it's brief it's useful information
GeneralMy vote of 5 Pin
Nithin Sundar25-Nov-10 18:34
memberNithin Sundar25-Nov-10 18:34 
GeneralMy vote of 5 Pin
Sayem Ahmed2-Oct-10 20:28
memberSayem Ahmed2-Oct-10 20:28 
QuestionHow images are serilized? Pin
Member 471108727-Sep-10 3:10
memberMember 471108727-Sep-10 3:10 
GeneralThe article is complete but far from perfect Pin
Simon Dufour14-Jul-10 5:18
memberSimon Dufour14-Jul-10 5:18 
AnswerRe: The article is complete but far from perfect Pin
Mazen el Senih6-Apr-12 5:47
memberMazen el Senih6-Apr-12 5:47 
GeneralThanks Pin
xliqz4-Feb-10 8:01
memberxliqz4-Feb-10 8:01 
Generalfilehandling Pin
M.YASIR ALI7-Dec-09 11:33
memberM.YASIR ALI7-Dec-09 11:33 
GeneralNice Pin
Nitin Sawant30-Nov-09 23:15
memberNitin Sawant30-Nov-09 23:15 
Generalexcellent! Pin
alejandro29A28-Aug-09 3:54
memberalejandro29A28-Aug-09 3:54 
GeneralAwesome Pin
Anubisasc19-Jan-09 6:33
memberAnubisasc19-Jan-09 6:33 
GeneralISerializable, inheritance and GetObjectData Pin
devvvy9-Jan-09 15:09
memberdevvvy9-Jan-09 15:09 
GeneralRe: ISerializable, inheritance and GetObjectData Pin
devvvy9-Jan-09 16:02
memberdevvvy9-Jan-09 16:02 
QuestionCan I serialize whole object to xml? Pin
jeff wa27-Dec-08 12:50
memberjeff wa27-Dec-08 12:50 
QuestionWhat are the reasons to Serialize Pin
expresso10001-Oct-08 5:18
memberexpresso10001-Oct-08 5:18 
AnswerRe: What are the reasons to Serialize Pin
Aram Azhari30-Dec-08 5:37
memberAram Azhari30-Dec-08 5:37 
GeneralRe: What are the reasons to Serialize Pin
Jason Newland14-Oct-11 0:28
memberJason Newland14-Oct-11 0:28 
GeneralRe: What are the reasons to Serialize Pin
Aram Azhari14-Oct-11 1:48
memberAram Azhari14-Oct-11 1:48 
GeneralSerializing image data Pin
sohst9-Sep-08 5:33
membersohst9-Sep-08 5:33 
GeneralSerializing Lists/Arrays/etc. Pin
Thanks for all the fish13-Aug-07 14:28
memberThanks for all the fish13-Aug-07 14:28 
GeneralArrayList in my object Pin
Spyder_Snyper6-Aug-07 7:13
memberSpyder_Snyper6-Aug-07 7:13 
GeneralSerialize a complex class Pin
Nigel Bogle13-Apr-07 2:18
memberNigel Bogle13-Apr-07 2:18 
QuestionDoes this work with XMLSerialization? Pin
voodoo90558-Mar-07 10:16
membervoodoo90558-Mar-07 10:16 
QuestionCan I Serialize a Interface Pin
IvelinaDoycheva26-Nov-06 23:21
memberIvelinaDoycheva26-Nov-06 23:21 
AnswerRe: Can I Serialize a Interface Pin
Tim Wiffen7-Mar-07 3:48
memberTim Wiffen7-Mar-07 3:48 
GeneralXMLSerialization Pin
BVandenbon25-Oct-06 2:13
memberBVandenbon25-Oct-06 2:13 
QuestionShould implement the interface ISerializable? Pin
anees7729-Jun-06 0:40
memberanees7729-Jun-06 0:40 
AnswerRe: Should implement the interface ISerializable? Pin
Ganesh Paulraj6-Oct-06 4:12
memberGanesh Paulraj6-Oct-06 4:12 
AnswerRe: Should implement the interface ISerializable? Pin
tallgill27-Jun-07 6:20
membertallgill27-Jun-07 6:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151120.1 | Last Updated 1 Feb 2002
Article Copyright 2002 by omkamal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid