Serialization in C#
Oftentimes, we need to store objects in physical storage so they can be read back and converted back to an object. The process of storing an object in a physical storage is called serialization. The process of reading a serialized object back into memory is deserialization.
In simple words, serialization in C# is a process of storing the object instance in a persistent storage. Serialization stores the state of objects, i.e., member variable values, to persistent storage such as a disk. Deserialization is the reverse of serialization. It is 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#.
Here is how serialization works. Image source: Microsoft Docs.
Namespaces involved
The following namespaces are involved in the 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 variables, name, and age, with some default values. We will write this class to a disk file (temp.dat) using the 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 as follows.
- Create an instance of a File that will store serialized objects.
- Create a stream from the file object.
- Create an instance of BinaryFormatter.
- Call the 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 the deserialize method of the BinaryFormatter object.
Now, let us see an example where we have used a '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.
brian caudillPosted Apr 5, 2023, 5:57 PM
change this >> File f = new File("temp.dat"); Stream s = f.Open(FileMode.Create); to this >> Stream s = File.Open("scos.xml",FileMode.Create);
Jim AhoPosted Sep 27, 2022, 5:12 AM
"The process of storing an object to a physical storage is called serialization". Isn't this a bit misleading? Serialization rather refers to converting the object for storage somewhere else. To actually store something (send it across network etc) isn't serialization.
Amir KianPosted Jan 16, 2022, 7:52 PM
Yout mast use [Serializable] attribute above each classes that you want to be serialized.
Pradeep ChandranPosted Mar 29, 2019, 5:55 AM
I am having more no of data.... Is there any way to store it in any local variable and run it in batch process..
SubashPosted Sep 8, 2016, 2:54 AM
Good
sangram desaiPosted Mar 10, 2012, 2:20 AM
Below is link that may of interest to you http://msdotnetbuddy.blogspot.in/2010/01/object-serialization-in-c.html
Roman LevitskiyPosted Aug 2, 2011, 8:44 PM
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.
tracyPosted Dec 3, 2008, 9:03 AM
It's very helpful,,but preety that it's no use for me!
expresso naPosted Oct 1, 2008, 10:13 AM
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.
thenewbeePosted Jul 16, 2007, 3:52 AM
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