views:

77

answers:

2

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.

+10  A: 

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);
SelflessCoder
Thanks, with var keyword this can be reduced tovar a = method.Invoke(0, null);
rajesh pillai
+1  A: 

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);
 }
Gabriel McAdams