Discover and Invoke methods programmatically at runtime

I had a fairly simple problem recently (well, most problems are simple – solutions are not always so). I had an interface for a class that exposed about a dozen or so methods, and I needed to call them all, one at a time. The methods were parameterless and the return types were identical. Basically the methods was returning Generic dictionaries of Strings.

E.g.

IStaticData staticData = StaticDataImporterFactory.GetStaticDataAdapter();
Dictionary <string, string> dic = staticData.GetSomeValues();

Rather than writing code line by line that would call each method in that interface, I reflected (pun intended) there must be a better(?) way of doing this, and came up with the idea to use Reflection to discover the methods in the interface programmatically and then call them. Here is the code:

IStaticData staticData = StaticDataImporterFactory.GetStaticDataAdapter();
Type type = typeof(IStaticData);
System.Reflection.MethodInfo[] methodInfos = type.GetMethods();
foreach (System.Reflection.MethodInfo methodInfo in methodInfos)
{
  try
  {
    Dictionary result = (Dictionary)methodInfo.Invoke(staticData, null);
    // do whatever work I have to do with the result
  }
  catch (Exception ex)
  {
    // handle the error
    txtError.Text += "Could not execute " + methodInfo.Name + Environment.NewLine;
  }
 }

The above code relies on the assumption that the methods to call are parameterless. If you wish to pass parameters to the methods, have a look at MethodInfo.GetParameters() to determine at runtime what the parameters are, and you can then pass them as additional arguments to the Invoke method (noticed I passed null above?)

And the deed is done.

Cheers
Ash Moollan



This entry was posted on Monday, August 18th, 2008 at 5:11 pm and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Discover and Invoke methods programmatically at runtime”

  1. Eren Abuel

    Hey Ash! Remember me? (apologies if that sounded stalkerish) What’s the update, you still in Aus?

    Cheerio

  2. sandrar

    Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

Leave a Reply

Your comment