Use reflection to call generic method in Dynamics NAV2013

If you are in need of calling a DotNet method that is generic,usually written as class<T>.method<T>(parameters), you will discover that its not really possible with the standard way of calling a DotNet method with NAV2013.

You will get something like this, “The type of one or more arguments does not match the method’s parameter type” – And there are no way of getting rid of that with standard usage of DotNet variables.

But luckily, .NET has the reflection namespace that adds the possiblity to invoke a method through data. The following piece of codes calls the InserrAfterSelf method that is part of the OpenXML library.

First, we get the Type of the “ClonedRow” variable and get the MethodInfo of the method (variable “mi”). Then we need to call the “MakeGenericMethod” to create a MethodInfo that support a generic invoke. Parameters for MakeGenericMethod must be a array with the type of <T>, in my case the tableRow Type from OpenXML.

Now that we have a MethodInfo that supports generics, we just wee to create an array with the parameters for the actual call. Even though that with working with a method that only takes one parameter. (When programming in C#, the compiler will creates an array with one entry automatic, but not in NAV2013).

At last, we can invoke the generic method from NAV2013.

A fair warning at the end, Reflection is slow, so this is not the solution if you need to call the method a million times, if thats the case, consider to create a assembly and call that from NAV2013.