Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Generic method using runtime type and cast return object

Tags:

c#

generics

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

like image 704
markpirvine Avatar asked Dec 31 '10 13:12

markpirvine


1 Answers

The type IS determined at runtime. It's the type of the reference variable that is object, the actual instance is strongly typed.

That's the best that can be done, considering that you're using reflection to dynamically get access to a method that the compiler has no type information for -- it might not even exist in the build environment.

EDIT: If you know something about the type returned by Deserialize, then you can take advantage of delegate variance. For example:

Type tType = Type.GetType(pLoadOut.Type);
MethodInfo method = typeof(ApiSerialiseHelper).GetMethod("Deserialise", new Type[] { typeof(string) });
MethodInfo generic = method.MakeGenericMethod(tType);
Converter<string,ISomething> deser = (Converter<string,ISomething>)Delegate.CreateDelegate(typeof(Converter<string,ISomething>),generic);
ISomething result = deser(pLoadOut.Data);
like image 74
Ben Voigt Avatar answered Sep 24 '22 14:09

Ben Voigt