BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Reflection
.NET 2.0+

Invoking Methods Using Reflection

The twentieth part of the Reflection tutorial describes the use of reflection to invoke methods of object instances. This allows late bound objects to be activated and used without needing to know the actual type or an interface that it implements.

Invoking Methods

In the previous two articles in this series we have looked at how late-bound objects can be instantiated using reflection, and how their public and private properties and fields can be accessed and updated. You can use similar reflection techniques to execute methods, either those of objects that have been activated with late binding, or ones that have been constructed normally. You identify these methods using MethodInfo instances, which can be generated from method names held in strings. This makes this style of method invocation useful when the details of the members to call are provided via configuration.

To demonstrate how methods can be invoked via reflection we'll use the following class. To try the examples for yourself, add the class to a new console application and execute the samples from within the Main method.

public class Test
{
    public void ShowMessage()
    {
        Console.WriteLine("Hello, world!");
    }

    private static void StaticShowMessage(string message)
    {
        Console.WriteLine(message);
    }

    public void ShowType<T>()
    {
        Console.WriteLine(typeof(T));
    }
}

Invoking Instance Methods

For our first example we'll invoke a simple, public instance method. First we need to create the object that contains the method to run. As when we worked with fields and properties, we'll create the object in a late-bound fashion using the Activator class's CreateInstance method. Next we'll obtain a MethodInfo object for the method in question. In the code below, you can see that this is the ShowMessage method. Finally we execute the method by calling the MethodInfo's Invoke member.

Invoke has two parameters. The first is the object that the method should be executed against. In the example code this is the testInstance object. The second parameter receives an object array. Each item in the array is passed to one of the parameters of the member being invoked. In the first sample the target method has no parameters, so null is used. If parameters are present, the objects in the array must be provided in the right order and must be of the correct types. In addition to providing the values, the types of the array items are used to determine which version of an overloaded method should be executed.

Type testType = typeof(Test);
object testInstance = Activator.CreateInstance(testType);

MethodInfo toInvoke = testType.GetMethod("ShowMessage");
toInvoke.Invoke(testInstance, null);

/* OUTPUT

Hello, world!

*/

Invoking Static Methods

Static methods can be invoked using the same technique as described above. As an object is not required in order to use a static member, you do not need to instantiate the target type. You just have to obtain a MethodInfo object and call its Invoke method. When calling Invoke for a static method, the first argument is ignored, so a good option for readability is to pass a null reference.

In the next example we execute the private, static method, "StaticShowMessage". Note that the Test type is not instantiated and that null is provided as the first argument of the Invoke call. As the StaticShowMessage requires a message to be provided, we pass an object array containing one string.

Type testType = typeof(Test);
MethodInfo toInvoke = testType.GetMethod(
    "StaticShowMessage", BindingFlags.Static | BindingFlags.NonPublic);
toInvoke.Invoke(null, new object[] { "Goodbye, world!" });

/* OUTPUT

Goodbye, world!

*/

Invoking Generic Methods

The last type of method that you might want to invoke using reflection is the generic method. If you obtain a MethodInfo object for a generic method that has open type parameters, you need to convert it to a closed method before executing it. As we've seen in the "Reflecting Generic Method Information" article, you can perform this conversion using the MakeGenericMethod method, providing the actual types for the type arguments to its parameters. Once you have a closed method's MethodInfo object, Invoke works in the same manner as seen earlier.

The final example obtains a reference for the ShowType generic method with its open "T" type argument. This is transformed into a closed type of integer with MakeGenericMethod before the invocation.

Type testType = typeof(Test);
object testInstance = Activator.CreateInstance(testType);

MethodInfo openMethod = testType.GetMethod("ShowType");
MethodInfo toInvoke = openMethod.MakeGenericMethod(typeof(int));
toInvoke.Invoke(testInstance, null);

/* OUTPUT

System.Int32

*/
8 August 2012