Reflecting Parameters

I got a question last week from a gentleman asking how to tell what parameters were available for a particular method.  This is useful when you know that a method will be available on a class you are calling, but the method could have any parameters, or when you have used reflection to get the list of methods in your class, and need to pull out the parameter list for each.

The solution is actually quite simple:

First, let’s use the assumption that we know the method name.  To get the parameters once you have the method, use this code:

Object o = myAssembly.CreateInstance("ClassLibrary1.Class1");

Type myType = myAssembly.GetType("ClassLibrary1.Class1");
MethodInfo mi = myType.GetMethod("Go");
ParameterInfo[] arguements = mi.GetParameters();

 

Given any method, Go(), this will give us the list of parameters for this method.

When iterating through the members, there is a small catch.  If you are iterating through your members generally (methods, and properties) than you’ll need to first detect if the member is a method using,

if (mi.MemberType==MemberTypes.Method)

and then cast the MemberInfo object to a MethodInfo so that you can call GetParameters().  Forget this step and you’ll spend the rest of the day trying to figure out why your code won’t compile.

Related Post

  • Using Reflection to Load a Class in ASP.NETUsing Reflection to Load a Class in ASP.NET Last week, we took a look at creating a DAL that would allow us to swap out database providers without having to rewrite a lot of our code.  The only problem with the code I showed you is that...
  • Reflection and InterfacesReflection and Interfaces Today is the last official installment in the series on reflection.  If you've been following along, you've probably notice that calling code in other classes using reflection is a huge pain i...
  • Renaming Properties, Methods and VariablesRenaming Properties, Methods and Variables Have you ever written some code and named something one thing only to realize that it should be named something else? If you haven't you haven't been programming for very long.  Maybe you start...
  • Reflection – Accessing MethodsReflection – Accessing Methods Today is the next to last installment on reflection.  We will look at how to call methods and pass parameters.  This is going to look a lot like what we've already done in previous sessio...
  • How to evaluate technology choicesHow to evaluate technology choices My post yesterday about an easy way of implementing templated e-mail was met by a comment suggesting that using XSLT would allow for more flexibility.  Which is true.  Once it was sugges...