Reflecting Parameters

Tagged with:

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.

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Tagged with:
kick it on DotNetKicks.com

Leave a Reply