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:
Continues…
Pages: 1 2












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