1

Hello as the question describes im trying to invoke a method through reflection, which is fine and all if it was a void type. but string, bool, etc is not working. also with a return type. i haven't been able to find any useful references.

i have a Test Class which i used to call some test methods. all the void ones had worked fine. but the others were not calling at all.

internal class Test
{
    public static void Print()
    {
        Console.WriteLine("Test");
        Console.WriteLine("Testing an invoke method");
    }

    public static void CalcData()
    {
        Console.WriteLine("Test");
    }

    public static void DoSomething(int c, float f)
    {
        Console.WriteLine("Test");
    }

    public static string TestString(string s, int p, char f)
    {
        return "Happy Days";
    }
}

in my Main Method i would call t.GetMethod("Print").Invoke(t, null);

but i am unsure how i would call to pass in a parameter or even obtain a return type.

some insight on this would be greatly appreciated.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Krazor
  • 25
  • 1
  • 6
  • Possible duplicate of [How to use reflection to call method by name](http://stackoverflow.com/questions/3110280/how-to-use-reflection-to-call-method-by-name) – Eugene Podskal Jun 26 '16 at 11:21

1 Answers1

4

Have a look at the signature of MethodInfo.Invoke

public object Invoke(
    object obj,
    object[] parameters
)

You need to pass the parameters of the method in the parameters object[]. Note that the method returns an object, you just need to cast it to the result type.

A call to TestString should look like this:

var parameters = new object[]{"A string", 10, 'a'};
string result = (string) t.GetMethod("Print").Invoke(t, parameters);
mariosangiorgio
  • 5,520
  • 4
  • 32
  • 46
  • thank you this worked perfectly. well i had to make a hand full of adjustments but i can now call any method over the network like this with few restrictions =) – Krazor Jun 27 '16 at 11:02
  • Looks good to me. I want to know about the meaning of return values by the invoke method. for example if Invoke method returns 16 or 9. What error it is. When Invoke command returns 0, this means the command runs successfully. – Awais ali Sep 07 '20 at 06:26