Tag Archives: generics

Another use for .Net Generics

Some time ago I created a simple utility class to quickly serialize and deserialize objects at run-time. It worked ok but had one drawback (probably more but I’m dealing with one specific one here). Because it deals with objects at run time and before the advent of generics you had to pass the object type as a parameter around – possibly I could have kept it dealing with only objects but I was trying to make the calling code easier to maintain and read.

The old methods looked something like this:

static class SerializeUtils
{

public static string SerializeXML(object classToSerialize)
{

XmlSerializer ser = new XmlSerializer(classToSerialize.GetType());
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
ser.Serialize(writer, classToSerialize);
return sb.ToString();

}
public static object DeserializeXML(string serializedObject, System.Type typeOfObject)
{

XmlSerializer ser = new XmlSerializer(typeOfObject);
MemoryStream input = null;
object result = null;
input = new MemoryStream(System.Text.Encoding.Unicode.GetBytes(serializedObject));
input.Position = 0;
result = ser.Deserialize(input);
return result;

}

}

But then at one stage I thought why must the object type be passed as a parameter plus the calling code still has to cast it again. Thankfully Generics make all that easier. Look at this:

public static class SerializationUtils
{

public static string SerializeToXML<T>(T classToSerialize) where T : class
{

XmlSerializer ser = new XmlSerializer(typeof(T));
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
ser.Serialize(writer, classToSerialize);
return sb.ToString();

}

public static T DeserializeXML<T>(string serializedObject) where T : class
{

XmlSerializer ser = new XmlSerializer(typeof(T));
MemoryStream input = null;
T result = null;
input = new MemoryStream(System.Text.Encoding.Unicode.GetBytes(serializedObject));
input.Position = 0;
result = (T)ser.Deserialize(input);

return result;

}

}

In a way the methods still take the type as a ‘parameter’ but this is something the compiler can use at compile time as well – i.e. to make sure the input and return types are actually of the proper class. With the Deserialized method the calling code actually get a fully casted object back.

There you have it.