Search code examples
c#.net-standard-2.1

How to get a generic MethodInfo with Type.GetMethod(string name, int genericParameterCount, Type[] types)?


I am trying to get the MethodInfo of the specific method Interlocked.CompareExchange<T>(ref T, T, T) and tried the below code to no avail:

typeof(Interlocked).GetMethod(nameof(Interlocked.CompareExchange), 1, new Type[] { typeof(int), typeof(int), typeof(int) })

Note that typeof(int) is just a random type. All I need is the MethodInfo so that I can later use GetGenericMethodDefinition with different types.

What array of types should we pass to get the required method?


Solution

  • The solution turns out to be quite simple:

    Type genericType = Type.MakeGenericMethodParameter(0);
    Type[] types = new Type[] { genericType.MakeByRefType(), genericType, genericType };
    
    MethodInfo methodInfo = typeof(Interlocked).GetMethod(nameof(Interlocked.CompareExchange), 1, types);