Click here to Skip to main content
6,822,613 members and growing! (23,440 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Beginner

.NET / XML Serialization

By Sarafian

An article that tries to clear up the concept of serialization
C++/CLI, C#1.0, C#2.0, C#3.0, VB7.x, VB8.0, VB9.0, Windows, .NETCF, Mobile, .NET1.0, .NET1.1, .NET2.0, .NET3.0, .NET3.5, ASP.NET, Visual-Studio, WebForms, Dev
Posted:11 Oct 2007
Views:27,677
Bookmarked:14 times
Unedited contribution
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
10 votes for this article.
Popularity: 1.75 Rating: 1.75 out of 5
5 votes, 50.0%
1
2 votes, 20.0%
2
1 vote, 10.0%
3

4
2 votes, 20.0%
5

Introduction

Being a developer that takes a lot from the internet, i decided to contribute some of my own. I always had some vague concept of the .Net serialization and yesterday I understood exaxtly why. Internet could be a great resource but it can be also greatly misleading. Thiw article tries to clarify the concepts of .NET Serialization and XML Serialization

Background

When i first looked up the term serialization, basically i redirected to sites that explaing how to turn an object to an xml represantation. Lets call that XML Serialization, a term that i do not actually like. But .NET Serialization its not that. Its the mechanism to transport data through remoting.

XML Serialization

The majority of articles on the internet have it wrong. There is no need for the class to be marked as [Serializable] or implement ISerializable. XML Serialization actually uses reflection to find and public properties or fields and then create the corresponding xml node. Deserialization also works that way.

This is sample general class for producing xml string for an object and its reverse procedure

public class Serializer

     {

        public static string ObjectToString(object obj)

           {

                 try

                 {

                XmlSerializer serializer = new XmlSerializer(obj.GetType(), "");

                       StringWriter writer = new StringWriter();

                serializer.Serialize(writer, obj, null);

                       return writer.ToString();

                 }

                 catch(Exception)

                 {

                 }

                 return null;

           }

           

           public static bool StringToObject(string data,out object obj)

           {

            obj = null; 

            try

                 {

                XmlSerializer serializer = new XmlSerializer(obj.GetType(),"");

                       StringReader reader = new StringReader(data);

                       obj=serializer.Deserialize(reader);

                       return true;

                 }

                 catch(Exception)

                 {

                

                 }

                 return false;

           }

     }

.NET Serialization

One of the mostly noted feature of .NET was serialization. The feature is used to trasport data between remoting calls. Behind the scenes something like this happens for binary transport protocol

MemoryStream ms = new MemoryStream(); 

BinaryFormatter bFormatter = new BinaryFormatter();

Derialize

bFormatter.Serialize(ms, objectToSerialize); 

Deserialize

Object_Type obj = (Object_Type)bformatter.Deserialize(ms); 

The class to be serialized must be marked with the [Serializable] attribute and optionally must implement the ISerializable interface. .Net automated mechanism uses reflection to find whats needs to be serialized. Because this is not an xml serialization, class that implement IDictionary and other interfaces cannot be serialized.

In order for deserialization to work extra info is wrapped with the actual binary data that describes what data is for what in a matter of way. This makes the data produced larger but keeps the job done for every valid serializable class.

If we want to override this mechanism the class must implement the ISerializeble and a constructor with the below signature.

The void ISerializeble.GetObjectData (SerializationInfo info, StreamingContext ctxt) is called by the CLR to acquire the serialized data and the public MyObject(SerializationInfo info, StreamingContext ctxt) is used to populate the objects data according to serialization data usually received through a remoting call.

In the above methods because we know exactly what we are going to add to the serialization stream, we gain speed because reflection is not used.And if our data coding is clever enough we gain from the smaller size of data that needs to be transfered.

Points of Interest

As you can see .NET Serialization is entirely different concept from XML Serialization. In my opinion XML Serialization should only be used to Store configuration files and options class in a registry key.

For more info about how to implement a custom serialization and for performance gain data look at Tim Haynes Fast Serialization article, based on which i finally clarified things in my mind.

Any terminology I used like .NET Serialization and XML Serialization, might be incorrect.

History

Version 1.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Sarafian


Member
Alex Sarafian lives in Athens Greece and currently is working with Business scale application with .NET latest technologies

He has been developing applications for personal and friends usage with C++ using majorly Borland's various IDEs since 1994.
In 2002 began working for an R&D institute where he was introduced to C# which he worships ever since.

He has recently created a development blog http://sarafianalex.wordpress.com/

He loves core applications development and in his spare time he usualy "wastes" time in front of his media center pc watching sitcoms, preferable SCI-FI.
He wants to play chess but he can't find any real world players to hang out with.
Occupation: Software Developer (Senior)
Company: Orama Hellas
Location: Greece Greece

Other popular .NET Framework articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
GeneralMy vote of 2 Pinmemberpuromtec19:21 23 Feb '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 11 Oct 2007
Editor:
Copyright 2007 by Sarafian
Everything else Copyright © CodeProject, 1999-2010
Web20 | Advertise on the Code Project