At the Jax SQL Saturday I was asked to turn a .NET object into an xml file and then reverse the process.
Step 1: Serialization with extension methods
C# 3.0 comes with this cool feature called extension methods. This is syntactical sugar for static methods that allows for you to “add” methods to other objects. To write one of these write a static class with a static method that takes the type you want to extend as the first parameter. The only difference from what you would do normally is to add the keyword “this” before the first parameter. The beauty is that it feels very natural for developers to just type the variable name and press dot and they get your new method in the statement completion in VS. (BTW you can still call the method the way you would in C# 2.0) So with the method below we now have added a Serialize method to Object thus it is inherited everywhere in the entire object model!
public static void Serialize(this object o, string filename)
{
Type t = o.GetType();
if (t.IsSerializable)
{
XmlSerializer serializer = new XmlSerializer(t);
using (TextWriter tw = new StreamWriter(filename))
{
serializer.Serialize(tw, o);
tw.Close();
}
}
else
{
throw new InvalidOperationException(string.Format("Objects of type {0} are not serializable.", t.Name));
}
}
Step 2: De-serialization with generics
I like generics for the process of de-serializing, this allows my method to return a strongly typed copy of the object that was serialized to the file.
public static T DeSerializeObject<T>(string filename)
{
T t;
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader tr = new StreamReader(filename))
{
t = (T)serializer.Deserialize(tr);
tr.Close();
}
return t;
}
Use the method like this:
Serializer.DeSerializeObject<Customer>("customer.xml")
Customer c = new Customer { FirstName = "Shawn", LastName = "Weisfeld" };
c.Serialize("customer.xml");