Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » C# Language » Serializing Objects in C#

Serializing Objects in C#

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.

Page Views : 190783
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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#.

Namespaces involved

Following namespaces are involved in serialization process :

  • System.Runtime.Serialization
  • System.Runtime.Serialization.Formatters.Binary

Example 1

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class SerialTest
{
public void SerializeNow()
{
ClassToSerialize c=
new ClassToSerialize();
File f=
new File("temp.dat");
Stream s=f.Open(FileMode.Create);
BinaryFormatter b=
new BinaryFormatter();
b.Serialize(s,c);
s.Close();
}
public void DeSerializeNow()
{
ClassToSerialize c=
new ClassToSerialize();
File f=
new File("temp.dat");
Stream s=f.Open(FileMode.Open);
BinaryFormatter b=
new BinaryFormatter();
c=(ClassToSerialize)b.Deserialize(s);
Console.WriteLine(c.name);
s.Close();
}
public static void Main(string[] s)
{
SerialTest st=
new SerialTest();
st.SerializeNow();
st.DeSerializeNow();
}
}
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 valiables 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.

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.

Example 2

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class SerialTest
{
public void SerializeNow()
{
ClassToSerialize c=
new ClassToSerialize();
c.Name="bipin";
c.Age=26;
ClassToSerialize.CompanyName="xyz";
File f=
new File("temp.dat");
Stream s=f.Open(FileMode.Create);
BinaryFormatter b=
new BinaryFormatter();
b.Serialize(s,c);
s.Close();
}
public void DeSerializeNow()
{
ClassToSerialize c=
new ClassToSerialize();
File f=
new File("temp.dat");
Stream s=f.Open(FileMode.Open);
BinaryFormatter b=
new BinaryFormatter();
c=(ClassToSerialize)b.Deserialize(s);
Console.WriteLine("Name :" + c.Name);
Console.WriteLine("Age :" + c.Age);
Console.WriteLine("Company Name :" + ClassToSerialize.CompanyName);
Console.WriteLine("Company Name :" + c.GetSupportClassString());
s.Close();
}
public static void Main(string[] s)
{
SerialTest st=
new SerialTest();
st.SerializeNow();
st.DeSerializeNow();
}
}
public class ClassToSerialize
{
private int age;
private string name;
static string companyname;
SupportClass supp=
new SupportClass();
public ClassToSerialize()
{
supp.SupportClassString="In support class";
}
public int Age
{
get
{
return age;
}
set
{
age=
value;
}
}
public string Name
{
get
{
return name;
}
set
{
name=
value;
}
}
public static string CompanyName
{
get
{
return companyname;
}
set
{
companyname=
value;
}
}
public string GetSupportClassString()
{
return supp.SupportClassString;
}
}
public class SupportClass
{
public string SupportClassString;
}

Example 3

The final example shows how to serialize array of objects.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class SerialTest
{
public void SerializeNow()
{
ClassToSerialize[] c=
new ClassToSerialize[3];
c[0]=
new ClassToSerialize();
c[0].Name="bipin";
c[0].Age=26;
c[1]=
new ClassToSerialize();
c[1].Name="abc";
c[1].Age=75;
c[2]=
new ClassToSerialize();
c[2].Name="pqr";
c[2].Age=50;
ClassToSerialize.CompanyName="xyz";
File f=new File("temp.dat");
Stream s=f.Open(FileMode.Create);
BinaryFormatter b=
new BinaryFormatter();
b.Serialize(s,c);
s.Close();
}
public void DeSerializeNow()
{
ClassToSerialize[] c;
File f=
new File("temp.dat");
Stream s=f.Open(FileMode.Open);
BinaryFormatter b=
new BinaryFormatter();
c=(ClassToSerialize[])b.Deserialize(s);
Console.WriteLine("Name :" + c[2].Name);
Console.WriteLine("Age :" + c[2].Age);
Console.WriteLine("Company Name :" + ClassToSerialize.CompanyName);
s.Close();
}
public static void Main(string[] s)
{
SerialTest st=
new SerialTest();
st.SerializeNow();
st.DeSerializeNow();
}
}
public class ClassToSerialize
{
private int age;
private string name;
static string companyname;
public int Age
{
get
{
return age;
}
set
{
age=
value;
}
}
public string Name
{
get
{
return name;
}
set
{
name=
value;
}
}
public static string CompanyName
{
get
{
return companyname;
}
set
{
companyname=
value;
}
}
}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Bipin Joshi
Bipin Joshi is a programmer working in Mumbai(India).
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
ERrors in Program by thenewbee On July 16, 2007
1)File f=new File("temp.dat"); Shows error as static member cannot be ue to declare variable 2)Serialization exception thown as the class is not marked as SERIALIZABLE
Reply | Email | Modify 
Re: Errors in Program by Amartya On March 18, 2008
codes has some common errors Like in the file creation part that portion shd be like this-- FileInfo f = new FileInfo (@"C:\temp.dat"); FileStream s = f.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None); ClassToSerialize class and SupportClass shd be tagged as [Serializable] here is the complete code which will work--- using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; class SerialTest { public void SerializeNow() { ClassToSerialize c = new ClassToSerialize (); c.Name = "bipin"; c.Age = 26; ClassToSerialize.CompanyName = "xyz"; FileInfo f = new FileInfo (@"C:\temp.dat"); FileStream s = f.Open (FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None); BinaryFormatter b = new BinaryFormatter (); b.Serialize (s, c); s.Close (); } public void DeSerializeNow() { ClassToSerialize c = new ClassToSerialize (); FileInfo f = new FileInfo (@"C:\temp.dat"); FileStream s = f.Open (FileMode.Open); BinaryFormatter b = new BinaryFormatter (); c = (ClassToSerialize)b.Deserialize (s); Console.WriteLine ("Name :" + c.Name); Console.WriteLine ("Age :" + c.Age); Console.WriteLine ("Company Name :" + ClassToSerialize.CompanyName); Console.WriteLine ("Company Name :" + c.GetSupportClassString ()); s.Close (); } static void Main(string[] args) { SerialTest st = new SerialTest (); st.SerializeNow (); st.DeSerializeNow (); } } [Serializable] public class ClassToSerialize { private int age; private string name; static string companyname; SupportClass supp = new SupportClass (); public ClassToSerialize() { supp.SupportClassString = "In support class"; } public int Age { get { return age; } set { age = value; } } public string Name { get { return name; } set { name = value; } } public static string CompanyName { get { return companyname; } set { companyname = value; } } public string GetSupportClassString() { return supp.SupportClassString; } } [Serializable] public class SupportClass { public string SupportClassString; }
Reply | Email | Modify 
Anonymous by expresso On October 1, 2008
Why don't you also explain the intent and why you would need to serialize in context to a real-world example and REASON. Give me a situation where you need to serialize. Just showing how doesn't tell the intent or reason in a real situation. That is what really gets people to understand...situations in which you'd need to do this.
Reply | Email | Modify 
Not Bad by tracy On December 3, 2008
It's very helpful,,but preety that it's no use for me!
Reply | Email | Modify 
error by Roman On August 2, 2011
ClassToSerialize needs to have a [Serializable] attribute. Otherwise we get error: Type 'SerializeTesting.ClassToSerialize' in Assembly 'SerializeTesting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.