Reuse Your Code .. Generic Save/Load!

Introduction

The majority of projects I get stuck into, have a requirement to save/load some kind of object - be that a custom object that stores specific settings for the application (no, I DON'T want to slap them into app.config, thank you very much - that can get messy very fast), or a lightweight list of something I am using in my application. Invariably, it boils down to saving the blessed thing somewhere and then load it back - it should be simple, so I don't want to have to re-write the code every time or call on some heavy library to manage things for me. This short article describes some very simple code that has become a regular part of my "code toolbelt" - I use it pretty much every other day for something or other that involves serialization.

It's good to share, so enjoy. :)

NB

While the code described here is in C#, I have also provided a VB version in the download link. 

Background - The Way Things Were

To get started, let's start off with a very basic example class that we want to serialize. You know it - basic stuff, it has a constructor and a const that indicates where I want it to save.

  1. class SimpleClass {  
  2.     const string FileSavePath = @ "c:\data\SimpleClass.xml";  
  3.     public Guid ID {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     public string CityName {  
  8.         get;  
  9.         set;  
  10.     }  
  11.     public int Rank {  
  12.         get;  
  13.         set;  
  14.     }  
  15.     public bool Active {  
  16.         get;  
  17.         set;  
  18.     }  
  19.     public List < string > RandomList {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public SimpleClass() {  
  24.         ID = Guid.NewGuid();  
  25.         RandomList = new List < string > ();  
  26.     }  
  27. }   

In the past, when I wanted to save and load such an object, I would build customized save and load methods that called on the XMLSerializer class to convert my object to an XML representation, and a stream reader/writer to get the XML to/from disk. I'm sure you've done the same thing yourself on occasion.

Basic object save method

  1. public void BasicSave() {  
  2.     var xs = new XmlSerializer(typeof(SimpleClass));  
  3.     using(TextWriter sw = new StreamWriter(FileSavePath)) {  
  4.         xs.Serialize(sw, this);  
  5.     }  
  6. }   
Basic object load method
  1. public void BasicLoad() {  
  2.     var xs = new XmlSerializer(typeof(SimpleClass));  
  3.     using(var sr = new StreamReader(FileSavePath)) {  
  4.         var tempObject = (SimpleClass) xs.Deserialize(sr);  
  5.         ID = tempObject.ID;  
  6.         CityName = tempObject.CityName;  
  7.         Rank = tempObject.Rank;  
  8.         Active = tempObject.Active;  
  9.         RandomList = tempObject.RandomList;  
  10.     }  
  11. }  
These methods are fine. They work but I have to re-write them and customize them each time I reuse ... not great - we can do better!

Getting a Bit Abstract

The next step is to create a separate class to manage the save/load. With this, things are already better from a re-use point of view. Here, we have a class GenericUtils, and the save method.

The class is static, so I don't have to implicitly create it. The Save method takes an Object type "T", and two method params: 'FileName' - where we want the serialized object to save, and 'Object', the object itself that we are going to serialize. The method is a simple expansion of the original save method. The main difference is that instead of explicitly casting using the class 'SImpleObject', we rather extract the typeof the variable and use that as the XmLSerializer input param.

  1. public static class GenericUtils {  
  2.     public static bool Save < T > (string FileName, Object Obj) {  
  3.         var xs = new XmlSerializer(typeof(T));  
  4.         using(TextWriter sw = new StreamWriter(FileName)) {  
  5.             xs.Serialize(sw, Obj);  
  6.         }  
  7.         if (File.Exists(FileName)) return true;  
  8.         else return false;  
  9.     }  
  10. }   
Now, when we want to save, we call the generic method, passing in the object type <SimpleClass>, the fileName where we want to save, and a reference to the object being saved this.
  1. public bool SaveGeneric1(string fileName) {  
  2.     return GenericUtils.Save < SimpleClass > (fileName, this);  
  3. }  

So far so good. Let's look at the Load method.

Load returns a generic Object, and is called by sending in an object type and the path/name of the file where the object we want to access has been previously saved. It's the same code as before, but made general and abstracted.

The Load method checks to see if the file is being asked for exists, and assuming it does, it attempts to deserialize it. The main trick here is that we typecast the object type for the deserializer by using the generic T value that is sent in when we call the method.

  1. public static class GenericUtils {  
  2.     public static T Load < T > (string FileName) {  
  3.         Object rslt;  
  4.         if (File.Exists(FileName)) {  
  5.             var xs = new XmlSerializer(typeof(T));  
  6.             using(var sr = new StreamReader(FileName)) {  
  7.                 rslt = (T) xs.Deserialize(sr);  
  8.             }  
  9.             return (T) rslt;  
  10.         } else {  
  11.             return default (T);  
  12.         }  
  13.     }  
  14. }   
As for save, now when we want to load, we call the generic method, passing in the object type <SimpleClass>, the fileName where the serialized object that we want to load is located, and a reference to the object being saved this.
  1. public void LoadGeneric1(string fileName) {  
  2.     var fileData = GenericUtils.Load < SimpleClass > (fileName);  
  3.     ID = fileData.ID;  
  4.     CityName = fileData.CityName;  
  5.     Rank = fileData.Rank;  
  6.     Active = fileData.Active;  
  7. }  

OK, so that's a little bit cleaner, but we can do better!

When we save the object, we are always sending in the type to the save method. There's no need to do this. We can read the type on the fly just before we save. This cuts down some more code.

  1. public static bool Save2(string FileName, Object Obj) {  
  2.     var xs = new XmlSerializer(Obj.GetType());  
  3.     using(TextWriter sw = new StreamWriter(FileName)) {  
  4.         xs.Serialize(sw, Obj);  
  5.     }  
  6.     if (File.Exists(FileName)) return true;  
  7.     else return false;  
  8. }   
The change here, is that when we declare the XmlSerializer, instead of passing in the type received by the method being called, we get the type on the fly Obj.GetType().

This means that the calling code for the method is far cleaner.

  1. public bool SaveGeneric2(string fileName) {  
  2.     return GenericUtils.Save2(fileName, this);  
  3. }   
So, that's the whirlwind tour. There is more related code I use that serializes to JSON - I'll add that in when I get some time!
Until then, happy coding.


Recommended Free Ebook
Similar Articles