Feeds:
Posts
Comments

Posts Tagged ‘Serialization’

Introduction

When developping our applications we can experience than some reference types have the same behavior than value types. As a matter of fact there is no more references to the copied object . It’s the case for  System.String and System.Nullable<T> which are called immutable object because when affecting new value to these variables a perfect copy is created to set the new value.

Immutable objects have many advantages :

  • No side effect
  • Thread safe
  • Perfect key of map (because of their unchanging Hashcode)
  • A simple copy of the reference represent a implementation of the Cloneable interface

What’s happen when we want to persist these object, by disconnecting them around your system? As a matter of fact, when the object is immutable it is difficult to rebuilt the instance because of its only “getters” and readonly attributes.

Let’s see a possible solution by constructing an immutable class Person.

/// <summary>
    /// Immutable class Person
    /// </summary>
    [DataContract]
    public class Person
    {
        private static readonly DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Person));

        [DataMember]
        private readonly string m_Name;

        public Person(string name)
        {
            this.m_Name = name;
        }

        public String Name
        {
            get
            {
                return this.m_Name;
            }
        }
}

To proceed we’ll be using DataContractSerializer class to perform with DataContract & readonly attribute as DataMember : It serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. This class cannot be inherited (source msdn).

public String ObjectToXML()
{
      using (MemoryStream m = new MemoryStream())
      {
           dcSerializer.WriteObject(m, this);
           m.Position = 0;

           using (StreamReader reader = new StreamReader(m))
           {
                 return reader.ReadToEnd();
            }
      }
}

public static Person XmlToObject(String xmlStream)
{
       using (MemoryStream m = new MemoryStream())
       using (StreamWriter writer = new StreamWriter(m))
       {
            writer.Write(xmlStream);
            writer.Flush();
            m.Position = 0;
            return dcSerializer.ReadObject(m) as Person;
       }
}

And you can use it as following code :

Person p = new Person("Zizou");
String serializedZizou = p.ObjectToXml();
Person ObjectP = Person.XmlToObject(serializedZizou);
String name = ObjectP.Name;

Enjoy! 🙂

Read Full Post »