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;
}
}
}
balajirnaukri-12656, if this helps please login to Mark As Answer. | Alert Moderator