Call Generic method using runtime type and cast return object

Posted by markpirvine on Stack Overflow See other posts from Stack Overflow or by markpirvine
Published on 2010-12-31T13:49:33Z Indexed on 2010/12/31 13:54 UTC
Read the original article Hit count: 114

Filed under:
|

I'm using reflection to call a generic method with a type determined at runtime. My code is as follows:

Type tType = Type.GetType(pLoadOut.Type);
MethodInfo method = typeof(ApiSerialiseHelper).GetMethod("Deserialise", new Type[] { typeof(string) });
MethodInfo generic = method.MakeGenericMethod(tType);
generic.Invoke(obj, new object[] { pLoadOut.Data });

This works ok. However the generic.Invoke method returns an object, but what I would like is the type determined at runtime. Is this possible with this approach, or is there a better option?

Mark

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics