Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

Dynamic Method Invocation using Reflection
By Luke Venediger

Abstract

Reflection allows the developer to dynamically manipulate and inspect the members of objects, which includes their fields, methods and types. This is a consequence of C# being a managed language.

This Article demonstrates how the developer can use Reflection to dynamically locate and call methods within a class, including passing the respective parameters to the method and also manage any error conditions that could arise during this process.

This article requires that you have had exposure to C# and are comfortable with the language. The tutorial largely resides in the example provided, where you are shown how a method can be dynamically invoked using console input.

The Example: Bob’s Burger Barn

Bob’s Burger Barn is quite a modern restaurant that allows it’s customers to order their meals using a computer terminal. The user logs into the ordering application and sends commands to order what he wants. For example, if a customer wants to order a burger, he must use the “burger” command with the following syntax:

burger <bun type> <sauce name> <meat type>

Examples:

burger sesame chilli chicken

burger plain ketchup beef

Bob decided that since his Burger Barn’s menu changes so much, it is wiser for him to allow his ordering application as much flexibility as possible. His C# developer recognised his need and made all ordering method invocations and listing completely dynamic.

If a customer wants to order a burger, he types burger and the ordering application checks to see if it has a method called “burger”. If it does, then the three parameters are passed to the method using Reflection method invocation. If the number of parameters is not correct an exception is thrown and the user is prompted with an appropriate error message.

In this way, Bob can add new menu items to his ordering application and the application will automatically be able to list and invoke them.

Dynamically Invoking a Method

Bob’s clever C# Developer uses a series of easy steps to look a method up and then invoke it. All this is done inside the GetCommand() method. The first step he takes is to get the first space-seperated word from the console input string. He then gets a reflection or type representation of the object that he wants to call a method on, namely the DynamicMethods object.

Type thisType = this.GetType();

He then asks the Type object if the class it is reflecting holds a method with a name that matches the word he read in from the console. If there is such a method, a method descriptor object is returned in the form of MethodInfo:

MethodInfo theMethod = thisType.GetMethod(TheCommandString);

If the return value is not null then the method exists. Now that he has a method descriptor, he can find out about the method, such as it’s access properties (private, public, protected).

In his application he has made sure that the only methods he wants to list and invoke are those that are public, not static and which originate from the class DynamicMethods, and not from it’s base class Object. To do this he has created a method called CheckMethod(MethodInfo method) that returns TRUE if the method meets these criteria, and false if not. This prevents a sneaky customer from trying to call DynamicMethods.GetType() or DynamicMethods.Main() or DynamicMethods.GetHashCode(), which could lead to erroneous and unwanted results. After all, a food ordering system should only have food 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 two parameters. The first is the object instance who’s method must be invoked (in this case, the current object) and the second parameter is an array of objects which hold the parameters to be passed to the method. The C# Developer realises that he does not need to have an object array for his methods. Reflection will take the object array passed to the Invoke method and split it up so that each object in the array 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 the CLR tries to execute the method: thisType.GetMethod(TheCommandString)

TargetParameterCountException
Thrown when the number of parameters in the object array passed to MethodInfo.Invoke does not match the number of parameters required by the 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 the commands. 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.

DynamicMethods.cs