Take the 2-minute tour ×

I've got this class with a method that returns an object:

public class Deserializer<T>
    public static T FromJson(string json)
        return new JavaScriptSerializer().Deserialize<T>(json);

And I've got a Type. How do I create an instance of the Deserializer class based on a this type? The following obviously doesn't work:

var type = typeOf(MyObject);
var foo = Deserializer<type>.FromJson(json);
share|improve this question

3 Answers 3

up vote 8 down vote accepted

You could provide a non-generic version as well for consumers that don't know the type at compile-time (which is a good practice by the way when you are exposing an API):

public class Deserializer
    public static T FromJson<T>(string json)

    public static object FromJson(string json, Type type)
        return new JavaScriptSerializer().Deserialize(json, type);

Now, consumers that know the type at compile-time:

Foo foo = Deserializer.FromJson<Foo>(json);

and consumers that don't know the type at compile-time:

Type type = ...
object instance = Deserializer.FromJson(json, type);
share|improve this answer
It works, but remember to reference the right version of System.Web.Extensions (.NET 4/4.5) where the Deserialize method takes type as an argument :) –  Anders Nygaard Aug 21 '12 at 8:01

This is how you could do it, but it's not exactly optimal unless you absolutely must do it this way. Go with one of the other answers if you can!

dynamic result = typeof(Deserializer<>).MakeGenericType(type)
    .InvokeMember("FromJson", BindingFlags.Public | BindingFlags.Static |
                              BindingFlags.InvokeMethod, null, null,
                  new [] { json });
share|improve this answer
+1, Although you will need to create an instance to invoke this method. –  Tejs Aug 20 '12 at 22:13
I'm sure it works, but holy flying crackerjacks, Batman! That's not really the prettiest of answers :) –  Flater Aug 21 '12 at 8:15

You can't do this. Generic type parameters are statically bound (compile-time). You can't pass it a System.Type object.

For your simple example, You could (somewhat obviously) just use MyObject:

MyObject foo = Deserializer<MyObject>.FromJson(json);

If you could do this, what would the resultant type of FromJson be? How would you use that object?

Type t = ___;  // How do you get this?
??? foo = Deserializer<t>.FromJson(json);   // What datatype is foo?

What you're trying to do isn't a feature of a statically-typed language like C#. It's more of a dynamic language feature, like Python, where you just return whatever you want and do whatever you want to it.

share|improve this answer

Your Answer


