Search code examples
c#genericstypesgeneric-type-argument

How to turn a Type instance into a generic type argument


I basically have something like this:

void Foo(Type ty)
{
    var result = serializer.Deserialize<ty>(inputContent);
}

Foo(typeof(Person));

The Deserialize<ty> doesn't work because it expects Deserialize<Person> instead. How do I work around this?

I'd also like to understand how generics work and why it won't accept ty which is typeof(Person).

EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface.

EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly:

[JsonFilter(Param="test", JsonDataType=typeof(Person))]

Solution

Based on Marc and Anton's answers:

var result = typeof(JavaScriptSerializer).GetMethod("Deserialize")
                 .MakeGenericMethod(JsonDataType)
                 .Invoke(serializer, new object[] { inputContent });

Solution

  • If ty is known at compile-time, why don't just

    void Foo<T>()
    {
        var result = serializer.Deserialize<T>(inputContext);
    }
    

    Otherwise,

    MethodInfo genericDeserializeMethod = serializer.GetType().GetMethod("Deserialize");
    MethodInfo closedDeserializeMethod = genericDeserializeMethod.MakeGenericMethod(ty);
    closedDeserializeMethod.Invoke(serializer, new object[] { inputContext });