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

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail