Innovate or Go Home

Naveen Ajmal, Mohammed
posts - 2, comments - 7, trackbacks - 1

My Links

News

Article Categories

Archives

.Net Community Sites

Serialization

Serialization

It’s a process of persisting the state of an object to disk or any storage medium.

 

Why Serialization?

  • To re-create the object at a later stage.
  • To send object across application domains.

How to make a class serializable?

By using the [Serializable] attribute

[Serializable]

class Employee

{

      public int age;

      public string name;

}


How to serialize a serializable class?

//Initialize the object

                        Employee emp=new Employee();

                        emp.age=30;

                        emp.name="Mohammed Ajmal";

 

                        //Serialize the object

                        IFormatter formatter=new BinaryFormatter();

Stream stream=new FileStream("SerializedData.dat",

 FileMode.Create,

 FileAccess.Write,

 FileShare.None);

                        formatter.Serialize(stream,emp);

                        stream.Close();

 

                        //Deserialize object and read values

                        Stream deserStream=new FileStream("SerializedData.dat",

           FileMode.Open,

           FileAccess.Read,

           FileShare.Read);

Employee deserializedEmp=(Employee) formatter.Deserialize(deserStream);

                        deserStream.Close();

 

                        //Write the deserialized data

                        Console.WriteLine("Age = {0}",deserializedEmp.age);

                        Console.WriteLine("Name = {0}",deserializedEmp.name);

Note:    1. If portability is required use SoapFormatter instead of BinaryFormatter

            2. The Serializable attribute cannot be inherited

How to prevent few member variables from being serialized?

Use the [NonSerialized] attribute with the member variable

Ex.  [NonSerialized] public string name;

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Monday, September 20, 2004 6:00 PM |

Feedback

Gravatar

# re: Serialization

Hi Ajmal,
Nice Quick bit on Serialization basics.
A couple of introductory lines to support architectural decision on when to start thinking about using serialization during the SDLC of a project, would prepare teams better.
9/21/2004 10:42 AM | Amit Acharya
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: