Using .NET reflection to dynamically create methods with generic parameters

Following on from my post Dynamically creating C# code using the CodeDomProvider I’ve created a new type dynamically using the CodeDomProvider and I now need to use the type within a generic method call.

So to start with, I have a DataSerializer class (the basics are shown below – I’ve just distilled it down to the method signature that we’re interested in for this post)

public class DataSerializer<T> where T : new()
{
   public static IList<T> Deserialize(IDelimiterSeperatedReader dsr, 
              string data, DelimitedDeserializeOptions options)
   {
      // method implementaion
   }
   // other methods
}

From the previous post I have a dynamically created type (so I just have a Type object, the variable generatedType shown in the code below). I need to create a call to the static method (Deserialize) with this type as a type generic parameter.

Type generatedType = cr.CompiledAssembly.GetType("CsvGeneratedData");

Type[] arguments = { typeof(IDelimiterSeperatedReader), 
                  typeof(string), typeof(DelimitedDeserializeOptions) };

Type dataserializer = typeof (DataSerializer<>);
Type typedSerializer = dataserializer.MakeGenericType(generatedType);
MethodInfo mi = typedSerializer.GetMethod("Deserialize", 
               BindingFlags.Public | BindingFlags.Static, 
               null, arguments, null);

In the above the arguments variable is an array of Type’s in the order of the arguments the method Deserialize takes. We then use

This code creates the MethodInfo object but we now need to invoke the method itself, so we use the following Type dataserializer = typeof (DataSerializer<>) to create a DataSerializer but at this point it does not have the generic parameter assigned to it, so we then use MakeGenericType to assign the generic parameter to the dataserializer. Finally we get the method info. for the static method we want to call.

Now we need to invoke the method using the following

mi.Invoke(null, parameters);

where parameters is an object array with the relevant method arguments.