Hougaard.com – Applied Hacking

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.

1 thought on “Use reflection to call generic method in Dynamics NAV2013

  1. Hi,
    Very interesting post, not more speak about that.
    I’m studing how to convert code from C# to C/AL, I’m using the code or the following example:

    http://msdn.microsoft.com/en-GB/library/hh674188.aspx

    I’m tring to understand what I can do in C/AL and what no.
    I did the call to the webservice and recive a response, all that from C/AL except the declaretion of the DataContract that I inserted in an external DLL (I don’t know if is possible create that code in C/AL).
    My problem at the moment is when I want to read the response, for example the following line of code:

    int locNum = locationsResponse.ResourceSets[0].Resources.Length;

    If I try to access to the ResourceSets[0] I cannot because ResourceSets is an array of type Location[] and not an integer.
    I tried to apply your code but I didn’t understand if it is applicable in my case and what parameters pass during the invoke call.
    Let me know what do you think about.
    All the best
    Eclipses

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.