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.

1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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 =)
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.