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+

Reflecting Generic Method Information

The sixteenth part of the Reflection tutorial continues the examination of reflection when used with generics. This article looks at the processes for extracting information about generic methods, their type parameters and generic method definitions.

Creating a Closed Constructed Method from a Generic Method Definition

As with generic type definitions, you can create a closed constructed method from a generic method definition by providing a set of types to be assigned to the type parameters. You do this with the MakeGenericMethod method. The types to be applied are provided to a Type array parameter. They can also be provided as a comma-separated list as the parameter is decorated with the params keyword.

Type type = typeof(TestClass);
MethodInfo method = type.GetMethod("TestMethod");
MethodInfo closed = method.MakeGenericMethod(typeof(string), typeof(int));

Console.WriteLine(closed.GetGenericArguments().Length);
Console.WriteLine(closed.GetGenericArguments()[0]);
Console.WriteLine(closed.GetGenericArguments()[1]);

/* OUTPUT

2
System.String
System.Int32

*/

Getting a Method's Generic Method Definition

The last MethodInfo method we'll consider here is GetGenericMethodDefinition. This can be used for any type of generic method to create a new MethodInfo object representing the original method's generic method definition. To demonstrate, consider the following code. Here we create a closed constructed type for our test method, applying the string and int types to the type parameters. Next we use the GetGenericMethodDefinition method to get the definition for that constructed method. This gives us a MethodInfo object with the two original open parameters.

Type type = typeof(TestClass);
MethodInfo method = type.GetMethod("TestMethod");
MethodInfo closed = method.MakeGenericMethod(typeof(string), typeof(int));
MethodInfo definition = closed.GetGenericMethodDefinition();

Console.WriteLine(definition.GetGenericArguments().Length);
Console.WriteLine(definition.GetGenericArguments()[0]);
Console.WriteLine(definition.GetGenericArguments()[1]);

/* OUTPUT

2
T1
T2

*/
30 June 2012