rajesh pillai
rajesh pillai

Reputation: 8118

.NET reflection : How do I invoke a method via reflection that returns array of objects?

Had a quick question.. Googled but nothing worthwhile found..

I have a simple type like shown below.

public class DummyClass
{
    public string[] Greetings()
    {
         return new string[] { "Welcome", "Hello" };
    }
}

How can I invoke the "Greetings" method via reflection? Note the method returns array of strings.

Upvotes: 1

Views: 177

Answers (2)

Gabriel McAdams
Gabriel McAdams

Reputation: 58251

Here is the code you need to call a method using reflection (keep in ind - the MethodInfo.Invoke method' return type is "Object"):

    DummyClass dummy = new DummyClass();

    MethodInfo theMethod = dummy.GetType().GetMethod("Greetings", BindingFlags.Public | BindingFlags.Instance);
    if (theMethod != null)
    {
        string[] ret = (string[])theMethod.Invoke(dummy, null);
    }

Upvotes: 2

Jeff Cyr
Jeff Cyr

Reputation: 4864

Nothing special is required to invoke this kind of method:

object o = new DummyClass();

MethodInfo method = typeof(DummyClass).GetMethod("Greetings");
string[] a = (string[])method.Invoke(o, null);

Upvotes: 11

Related Questions