Monday, July 25, 2011

C# and .NET interview questions:- What is Serialization? Deserialization and how do you do it?

This is one of the most typical interview questions, which are asked in almost all of the interviews and is the favorable question of the interviewers.
Serialization: -“Serialization” is a process of converting an object into a stream of bytes.

Deserialization: - “Deserialization” is reverse of “serialization”, where stream of bytes are converted back in to an object.

Let’s see a simple example how exactly we can do “serialization” and “deserialization”.

It’s very simple four steps procedure as follows.

Step1: - create a new “window application” like below diagram.

Step2: - Now create a customer class in “Form1.cs” file.

Step3: - Now, we will see how exactly “serialization” is done.

Import the following namespace
using System.IO;

privatevoidSerialize_Click(object sender, EventArgs e)
Customerobj = newCustomer();// created instance of the customer class
obj.CustomerCode = textBox1.Text;
obj.CustomerName = textBox2.Text;
IFormatter formatter = newBinaryFormatter();
Streamstream = newFileStream("E:\\Customer.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
textBox1.Text = "";
textBox2.Text = "";

Step4: - Similarly, we will do for “deserialization”.

privatevoidDeserialize_Click(object sender, EventArgs e)
IFormatter formatter = newBinaryFormatter();
Streamstream = newFileStream("E:\\Customer.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
Customerobj = (Customer)formatter.Deserialize(stream);
textBox1.Text = obj.CustomerCode;
textBox2.Text = obj.CustomerName;

Once you have completed all the above steps now you can run your application and see the respective result.

View more C# and Dotnet interview questions


View more authors learning tutorials on Most asked c# interview questions

No comments: