Click here to Skip to main content
13,301,510 members (93,000 online)
Click here to Skip to main content
Add your own
alternative version


64 bookmarked
Posted 22 Sep 2004

A Simple Serializer / Deserializer

, 22 Sep 2004
Rate this:
Please Sign up or sign in to vote.
A simple Serializer / Deserializer.


I needed a simple serialization / deserialization mechanism to save and load state information for objects whose type (the class) is constructed and compiled at runtime (see my article on Declaratively Populating A PropertyGrid). Neither XmlSerializer nor BinaryFormatter classes handle this scenario. So, I wrote a lightweight assembly to handle my specific needs.


The serializer consists of three steps:

  1. Initialize using the Start() method
  2. Serialize one or more objects to XML
  3. Finish the process with the Finish() method


This is very straight forward. A MemoryStream and XmlTextWriter are constructed and the initial XML document is setup:

public void Start()
    ms=new MemoryStream();
    xtw = new XmlTextWriter(ms, Encoding.UTF8);

The Serializer

The serializer does a few important things and has a few limitations:

  • it serializes only public properties and enumerations that are writeable
  • it ignores arrays
  • it looks for a [DefaultValue] attribute decorating the property, and if it exists and the property value equals the default value, the property is not serialized
  • it uses a type converter to convert the property value to a string, rather than the ToString() method. This allows deserialization to work on Font, Color, and other classes that know how to serialize to a string
  • it serializes only properties with the IsSerializable flag set in the property type
  • it does not walk the object graph to serialize child classes
// simple property serialization
public void Serialize(object obj)
  Trace.Assert(xtw != null, "Must call Serializer.Start() first.");
  Trace.Assert(obj != null, "Cannot serialize a null object.");

  Type t=obj.GetType();
  foreach(PropertyInfo pi in t.GetProperties())
    Type propertyType=pi.PropertyType;
    // with enum properties, IsPublic==false, even if marked public!
    if ( (propertyType.IsSerializable) && (!propertyType.IsArray) &&
         (pi.CanWrite) && ( (propertyType.IsPublic) || (propertyType.IsEnum) ) )
      object val=pi.GetValue(obj, null);
      if (val != null)
        bool isDefaultValue=false;
        // look for a default value attribute.
        foreach(object attr in pi.GetCustomAttributes(false))
          if (attr is DefaultValueAttribute)
            // it exists--compare current value to default value
            DefaultValueAttribute dva=(DefaultValueAttribute)attr;

        // only non-default values or properties without a default value are 
        // serialized.
        if (!isDefaultValue)
          // do a type conversion to a string, as this yields a
          // deserializable value, rather than what ToString returns.
          TypeConverter tc=TypeDescriptor.GetConverter(propertyType);
          if (tc.CanConvertTo(typeof(string)))
            val=tc.ConvertTo(val, typeof(string));
            xtw.WriteAttributeString(pi.Name, val.ToString());
            Trace.WriteLine("Cannot convert "+pi.Name+" to a string value.");
        // null values not supported!


The Finish() method cleans up the text writer and returns the XML:

public string Finish()
    Trace.Assert(xtw != null, "Must call Serializer.Start() first.");

    Encoding e8=new UTF8Encoding();
    xml=e8.GetString(ms.ToArray(), 1, ms.ToArray().Length-1);
    return xml;


The deserializer expects that the instance has already been constructed. This is a very helpful shortcut to take, because constructing an object at runtime often requires a fully qualified assembly name, namespace, and other information. Furthermore, the type information for my runtime constructed classes is actually not available--only the instance is. For my particular requirement, this is not an issue.

Also, the deserializer will inspect each property for a default value and restore that value to the specified object unless it is being overridden in the XML.

Finally, when deserializing multiple objects, you must know the exact sequence that was used to serialize the objects, as an index pointing to the serialized object's element is passed in to the deserializer. Again, for my purposes, this restriction is not an issue.

// simple property deserialization
public void Deserialize(object obj, int idx)
  Trace.Assert(doc != null, "Must call Deserializer.Start() first.");
  Trace.Assert(doc.ChildNodes.Count==3, "Incorrect xml format.");
  Trace.Assert(idx < doc.ChildNodes[2].ChildNodes.Count,
                 "No element for the specified index.");
  Trace.Assert(obj != null, "Cannot deserialize to a null object");

  // skip the encoding and comment, and get the indicated
  // child in the Objects tag
  XmlNode node=doc.ChildNodes[2].ChildNodes[idx];
  Type t=obj.GetType();
  Trace.Assert(t.Name==node.Name, "Object name does not match element tag.");

  // set all properties that have a default value and not overridden.
  foreach(PropertyInfo pi in t.GetProperties())
    Type propertyType=pi.PropertyType;

    // look for a default value attribute.
    foreach(object attr in pi.GetCustomAttributes(false))
      if (attr is DefaultValueAttribute)
        // it has a default value
        DefaultValueAttribute dva=(DefaultValueAttribute)attr;
        if (node.Attributes[pi.Name] == null)
          // assign the default value, as it's not being overridden.
          // this reverts the object's property back to the default
          pi.SetValue(obj, dva.Value, null);

  // now parse the xml attributes that are going to change property values
  foreach(XmlAttribute attr in node.Attributes)
    string pname=attr.Name;
    string pvalue=attr.Value;
    PropertyInfo pi=t.GetProperty(pname);
    if (pi != null)
      TypeConverter tc=TypeDescriptor.GetConverter(pi.PropertyType);
      if (tc.CanConvertFrom(typeof(string)))
          object val=tc.ConvertFrom(pvalue);
          pi.SetValue(obj, val, null);
        catch(Exception e)
          Trace.WriteLine("Setting "+pname+" failed:\r\n"+e.Message);


Usage is very simple. Let's say we want to serialize a simple class (in this example, one that is constructed at compile time):

public class TestClass
    protected string firstName;
    protected string lastName;

    public string FirstName
        get {return firstName;}
        set {firstName=value;}

    public string LastName
        get {return lastName;}
        set {lastName=value;}

    public TestClass()

Serializing an instance of this class would look like this:

Serializer s=new Serializer();
TestClass tc=new TestClass();
string text=s.Finish();

Resulting in XML that looks like this:

<?xml version="1.0" encoding="utf-8"?> 
  <TestClass FirstName="Joe" LastName="Smith" /> 

Deserialization of this object is done as:

Deserializer d=new Deserializer();
TestClass tc=new TestClass();
d.Deserialize(tc, 0);

After which, the properties of the class are set to "Joe" and "Smith".


11/30/04 - Added support for property types that implement IList.


The code presented above meets a very specific requirement that I have. Even if you don't have this requirement, hopefully you'll gain something from the techniques demonstrated, especially the use of the type converter to convert to and from a string. This is an important "trick" to ensure that the serialized string is in a format that the deserializer can handle and avoids writing special case code for Font, Color, and other objects.


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

Marc Clifton
United States United States
Marc is the creator of two open source projects, MyXaml, a declarative (XML) instantiation engine and the Advanced Unit Testing framework, and Interacx, a commercial n-tier RAD application suite.  Visit his website,, where you will find many of his articles and his blog.

Marc lives in Philmont, NY.

You may also be interested in...


Comments and Discussions

Questionworks great...except Pin
Aaron Sulwer24-Jul-14 12:07
memberAaron Sulwer24-Jul-14 12:07 
GeneralMy vote of 4 Pin
Member 1067919018-Mar-14 2:39
memberMember 1067919018-Mar-14 2:39 
GeneralEror Message [modified] Pin
antoschka18-Jan-09 21:53
memberantoschka18-Jan-09 21:53 
GeneralBrilliant Article! Pin
lhayes0028-Apr-08 14:46
memberlhayes0028-Apr-08 14:46 
Very interesting article! 5/5
GeneralSave to SQL Server 2005 Pin
hugobq7-Jun-06 9:11
memberhugobq7-Jun-06 9:11 
GeneralRe: Save to SQL Server 2005 Pin
Marc Clifton8-Jun-06 15:31
protectorMarc Clifton8-Jun-06 15:31 
GeneralBugs Pin
janpub4-Sep-05 4:02
memberjanpub4-Sep-05 4:02 
Generallightweight class to serialize/deserialise object and xml string Pin
Leon Loguinov20-Oct-04 10:55
memberLeon Loguinov20-Oct-04 10:55 
GeneralRe: lightweight class to serialize/deserialise object and xml string Pin
Marc Clifton20-Oct-04 11:06
protectorMarc Clifton20-Oct-04 11:06 
GeneralRe: lightweight class to serialize/deserialise object and xml string Pin
FocusedWolf7-Dec-05 9:28
memberFocusedWolf7-Dec-05 9:28 
GeneralRe: lightweight class to serialize/deserialise object and xml string Pin
FocusedWolf8-Dec-05 19:15
memberFocusedWolf8-Dec-05 19:15 
GeneralNice Work Pin
Nick Parker22-Sep-04 10:25
protectorNick Parker22-Sep-04 10:25 
GeneralNice idea with the TypeConverter Pin
Mike Ellison22-Sep-04 8:40
memberMike Ellison22-Sep-04 8:40 
GeneralRe: Nice idea with the TypeConverter Pin
Arun Bhalla28-Sep-04 17:25
memberArun Bhalla28-Sep-04 17:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 22 Sep 2004
Article Copyright 2004 by Marc Clifton
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid