Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

Reflection, Get return value from a method

How can we exacute a method and get the return value from Reflection.

Type serviceType = Type.GetType("class", true);
var service = Activator.CreateInstance(serviceType);
serviceType.InvokeMember("GetAll", BindingFlags.InvokeMethod, Type.DefaultBinder, service, null);

Upvotes: 2

Views: 8387

Answers (4)

sandyiit
sandyiit

Reputation: 1705

I am not sure whether you are interested on the return value or the return Type. Well both are answered by the code below, where I try to execute the sum method and get the value as well as the Type of the return value:

class Program
{
    static void Main(string[] args)
    {
        var svc = Activator.CreateInstance(typeof(Util));
        Object ret = typeof(Util).InvokeMember("sum", BindingFlags.InvokeMethod, Type.DefaultBinder, svc, new Object[] { 1, 2 });
        Type t = ret.GetType();

        Console.WriteLine("Return Value: " + ret);
        Console.WriteLine("Return Type: " + t);
    }
}

class Util
{
    public int sum(int a, int b)
    {
        return a + b;
    }
}

Upvotes: 4

Adrian Fâciu
Adrian Fâciu

Reputation: 12552

You can try something like this:

ConstructorInfo constructor = Type.GetType("class", true).GetConstructor(Type.EmptyTypes);
object classObject = constructor.Invoke(new object[]{});

MethodInfo methodInfo = Type.GetType("class", true).GetMethod("GetAll");
object returnValue = methodInfo.Invoke(classObject , new object[] { });

I haven't compiled it, but it should work.

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33252

cast the InvokeMember result to the type actually returned by the method call.

Upvotes: 1

abieganski
abieganski

Reputation: 560

http://msdn.microsoft.com/en-us/library/de3dhzwy.aspx

"Return Value

Type: System.Object

An object representing the return value of the invoked member."

Upvotes: 1

Related Questions