views:

43

answers:

2

In C# I want to create a generic method that:

  1. Accepts a MethodInfo object as a parameter.
  2. Returns the object that is returned when the MethodInfo is invoked.

The source of my confusion is that I want the method to be generically typed to the same return type as the MethodInfo object that gets passed in.

+3  A: 

You cannot do this. By definition, generics are a compile-time construct, while the return type of a particular MethodInfo is something that is only known at runtime (when you receive a specific MethodInfo instance), and will change from call to call.

Pavel Minaev
A: 

Pavel Minaev is right,

My suggestion in this case (of course i don't know the whole context) is use a method that returns a dynamic type, of course is that wouldn't be typed.

public dynamic MyMethod(MethodInfo methodInfo)

Or since you know what is the return type, put that in the method call:

public T MyMethod<T>(MethodInfo methodInfo)

of course you gonna get in trouble inside the method mapping the conversions. but you can also put the conversion in a parameter using lambda, like:

public T MyMethod<T>(MethodInfo methodInfo, Func<object, T> conversion)

i think the call of the method will be very clear, like:

Console.WriteLine(MyMethod(methodInfo, (a) => Convert.ToString(a)));
Leo Nowaczyk