Call static method with reflection

Tono Nam picture Tono Nam · Aug 10, 2012 · Viewed 103.8k times · Source

I have several static classes in the namespace mySolution.Macros such as

static class Indent{    
     public static void Run(){
         // implementation
     }
     // other helper methods
}

So my question is how it will be possible to call those methods with the help of reflection?

If the methods where NOT to be static then I could do something like:

var macroClasses = Assembly.GetExecutingAssembly().GetTypes().Where( x => x.Namespace.ToUpper().Contains("MACRO") );

foreach (var tempClass in macroClasses)
{
   var curInsance = Activator.CreateInstance(tempClass);
   // I know have an instance of a macro and will be able to run it

   // using reflection I will be able to run the method as:
   curInsance.GetType().GetMethod("Run").Invoke(curInsance, null);
}

I will like to keep my classes static. How will I be able to do something similar with static methods?

In short I will like to call all the Run methods from all the static classes that are in the namespace mySolution.Macros.

Answer

Lee picture Lee · Aug 10, 2012

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

As the comment points out, you may want to ensure the method is static when calling GetMethod:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);