Dynamic Method Invocation in C# using Reflection
Abstract
Reflection allows the developer todynamically manipulate and inspect the members of objects, whichincludes their fields, methods and types. This is a consequence of C#being a managed language.
This Article demonstrates how the developercan use Reflection to dynamically locate and call methods within aclass, including passing the respective parameters to the method andalso manage any error conditions that could arise during this process.
This article requires that you have hadexposure to C# and are comfortable with the language. The tutoriallargely resides in the example provided, where you are shown how amethod can be dynamically invoked using console input.
The Example: Bob�s Burger Barn
Bob�s Burger Barn is quite amodern restaurant that allows it�s customers to order their meals usinga computer terminal. The user logs into the ordering application andsends commands to order what he wants. For example, if a customer wantsto order a burger, he must use the �burger� command with the followingsyntax:
burger <bun type> <sauce name> <meat type>
Examples:
burger sesame chilli chicken
burger plain ketchup beef
Bob decided that since his Burger Barn�s menuchanges so much, it is wiser for him to allow his ordering applicationas much flexibility as possible. His C# developer recognised his needand made all ordering method invocations and listing completelydynamic.
If a customer wants to order a burger, he types burger<param1><param2><param3>and the ordering application checks to see if it has a method called�burger�. If it does, then the three parameters are passed to themethod using Reflection method invocation. If the number of parametersis not correct an exception is thrown and the user is prompted with anappropriate error message.</param3></param2></param1>
Inthis way, Bob can add new menu items to his ordering application andthe application will automatically be able to list and invoke them.
Dynamically Invoking a Method
Bob�s clever C# Developer uses a series ofeasy steps to look a method up and then invoke it. All this is doneinside the GetCommand() method. The first step he takes is to get thefirst space-seperated word from the console input string. He then getsa reflection or type representation of the object that he wants to calla method on, namely the DynamicMethods object.
Type thisType = this.GetType();
He then asks the Type object ifthe class it is reflecting holds a method with a name that matches theword he read in from the console. If there is such a method, a methoddescriptor object is returned in the form of MethodInfo:
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
If the return value is not null then themethod exists. Now that he has a method descriptor, he can find outabout the method, such as it�s access properties (private, public,protected).
In his application he has made sure that theonly methods he wants to list and invoke are those that are public, notstatic and which originate from the class DynamicMethods, and not fromit�s base class Object. To do this he has created a method calledCheckMethod(MethodInfo method) that returns TRUE if the method meetsthese criteria, and false if not. This prevents a sneaky customer fromtrying to call DynamicMethods.GetType() or DynamicMethods.Main() orDynamicMethods.GetHashCode(), which could lead to erroneous andunwanted results. After all, a food ordering system should only havefood ordering functionality!
After making sure that he really wants this method to be invoked, our valiant C# Developer invokes the method:
theMethod.Invoke(this, userParameters);
The MethodInfo.Invoke method takes twoparameters. The first is the object instance who�s method must beinvoked (in this case, the current object) and the second parameter isan array of objects which hold the parameters to be passed to themethod. The C# Developer realises that he does not need to have anobject array for his methods. Reflection will take the object arraypassed to the Invoke method and split it up so that each object in thearray is passed as an individual parameter when the method is called.
All the above operations are done within a Try-Catch block so that the C# Developer can trap for the following error conditions
ArgumentNullException
Thrown when the user enters in a blank line as console input and theCLR tries to execute the method: thisType.GetMethod(TheCommandString)
TargetParameterCountException
Thrown when the number of parameters in the object array passed toMethodInfo.Invoke does not match the number of parameters required bythe method declaration.
Running The Example
To run the example, download the source and compile it using the following line:
csc DynamicMethods.cs
To get help, type �help� and try some of thecommands. Check out the �list� command. It is done using the method�DynamicMethods.List�, and is completely dynamic.
The example is written for C#.NET Beta 2.




28. May, 2006 by 







No comments yet... Be the first to leave a reply!