.NET
  Home arrow .NET arrow Page 4 - Delving Deeper into Serialization with .NE...
Moblin
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
JMSL Numerical Library 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
.NET

Delving Deeper into Serialization with .NET
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2007-08-15

    Table of Contents:
  • Delving Deeper into Serialization with .NET
  • A Caution on Serialization and Inheritance
  • ISerializable
  • Deserialization

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Delving Deeper into Serialization with .NET - Deserialization


    (Page 4 of 4 )

    Now, an instance of User can be serialized. However, we need to provide a way for an object to be deserialized as well; this is not done for us. We have to pull our value back out and assign it to the proper place. Additionally, we need to give sessionStartTime a value as well. This is all done through a constructor, whose parameters match the parameters of GetObjectData. The constructor is automatically called upon deserialization, and if it's absent, an exception will be raised. Here's the required code:

    public class User : ISerializable

    {

       ...

       protected User(SerializationInfo info, StreamingContext context)

       {

           name = info.GetString("name");

           sessionStartTime = DateTime.Now;

       }

       ...

    }

    Notice how the new constructor is protected. This is to prevent an external source from manipulating private data. Otherwise, information could be loaded with undesirable values.

    Now, User is ready for serialization and deserialization:

    using System;

    using System.IO;

    using System.Runtime.Serialization.Formatters.Binary;

     

    class UsingISerializable

    {

       public static void Main(string[] args)

       {

           // Create a User

           User dan = new User("Dan");

           Console.WriteLine("{0}, logged on since {1}.", dan.Name, dan.SessionStartTime);

           

           // Serialize dan

           MemoryStream myStream = new MemoryStream();

           BinaryFormatter formatter = new BinaryFormatter();

           formatter.Serialize(myStream, dan);

           

           // Deserialize dan

           myStream.Position = 0;

           dan = (User)formatter.Deserialize(myStream);

           myStream.Close();

           Console.WriteLine("{0}, logged on since {1}.", dan.Name, dan.SessionStartTime);

       }

    }


    Dan, logged on since 8/3/2007 7:09:58 PM.

    Dan, logged on since 8/3/2007 7:09:59 PM.

    Earlier, we looked at inheritance with .NET's automatic method of serialization. .NET handled the private data defined by our sample base class, Shape. However, with ISerializable, this isn't the case. For a child class to be properly serialized, it needs to override GetObjectData, wherein it needs to call its base class' GetObjectData method (this is why we set User's as virtual). The child class also needs to call its parent class' constructor. Let's create a class called Administrator, which will inherit from User, to demonstrate this:

    [Serializable]

    public class Administrator : User

    {

       public Administrator(string name)

           : base(name)

       {

           // initialize data

       }

       protected Administrator(SerializationInfo info, StreamingContext context)

           : base(info, context)

       {

           // restore data

       }

       

       public override void GetObjectData(SerializationInfo info, StreamingContext context)

       {

           base.GetObjectData(info, context);

           // add data to info

       }

    }

    So, why use ISerializable over .NET's default method of serialization? Actually, in most cases, you shouldn't. As you've probably noticed, using ISerializable is far more complicated and messier, and it's actually slower. Unless you have a really good reason to use ISerializable, stick with the default method. If you need control over the serialization and deserialization processes, simply use the attributes discussed in the last part. Moreover, the attribute approach is more readable. Rather than looking through the GetObjectData method to discover what members are serialized and what members are not, one can just look at the member itself.

    Conclusion

    Serialization is a powerful technique for persisting objects. In the first part, we examined how to use .NET's default, attribute-based serialization method, and we saw how to participate in this process by using special attributes and methods. In this part, we looked at how inheritance affects the serialization process. We also looked at the ISerializable interface, which offers a more manual approach to serialization. However, serialization does not end there: there are many more serialization-related features to the framework that merit looking into.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Hello, all!In Serialization with .NET, I explained how to use automatic...
     

    .NET ARTICLES

    - More on Commands, Input and the WPF
    - Grouping and Aggregating When Querying LINQ ...
    - Commands, Input and the WPF
    - Keyboard and Ink Input with WPF
    - Mouse Input and the WPF
    - Input with Windows Presentation Foundation
    - Introducing LINQ with XML and Databases
    - An Introduction to LINQ
    - Querying LINQ to SQL: Basics
    - Completing a Simple Storefront with LINQ
    - Knowing Your Environment: the System.Environ...
    - Creating the Home Page for a Simple Storefro...
    - LINQ Quickly with Language Integrated Queries
    - Introducing LINQ to SQL Designer using Visua...
    - Beginning LINQ to SQL Using Visual Studio 20...

    Iron Speed




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway