views:

90

answers:

2

I'm pulling serialized data from a database along with an object type (where one field contains the object type and one contains an XML string of serialized data).

I've got a generic serializer that has a serialize and deserialize method:

public static class Serializer<T>
{
    public static string Serialize(T objectData) { }
    public static T Deserialize(string xmlData) { }
}

Given that the object type is specified in the database field, is there any way for me to dynamically set what T is? - This is my line of thought (although this doesn't work):

Type t = Type.GetType(objectTypeName);
t objData = Serializer<t>.Deserialize(objectXmlString);

I was hoping to refactor some code out of a switch statement where T is a set value, but I can't figure out if it can be done, or if so, how I would go about that.

Thanks in advance.

A: 

No. However, it should not be too difficult to create additional overloads of your serialisation methods to handle this requirement:

public string Serialize(Type objectType, object objectData) { }
public object Deserialize(Type objectType, string xmlData) { }

The serialisation APIs in .NET all take Type instances as parameters anyway.

Christian Hayter
+5  A: 

You can do this, but it involves reflection - MakeGenericType, in particular:

typeof(Serializer<>).MakeGenericType(t).GetMethod("Deserialize").Invoke(...);

I haven't completed that, since your example is confusing; the method is instance, but is called as though it were static.

Interestingly (perhaps), dynamic might make this easier in 4.0 - I don't have my VM to hand, but imagine:

static void SomeGenericMethod<T>(T arg) { Serializer<T>.SomeMethod(arg); }
...
dynamic obj = ...
SomeGenericMethod(obj);

I'd need to check, but I expect that would do a lot of the heavy lifting for us.

The other common approach is to expose methods that work on a Type, rather than via generics.

Marc Gravell
Wow! I never knew that! Very useful.
Mongus Pong
Oops, that'll teach me to code right into SO. I did mean to write them as static methods. Thanks for pointing that out.
BenAlabaster