title: Invoke Static Generic Method via delegate via Emit
body: <p>I try to create a deleagte to invoke a  static generic Method. But I got the error: Invalid code detected! nyone a idea what is wrong with my IL?</p>
  
  <p>The FindStaticMethod Call in the Example Code is working and Returning a Method Info, with the given Type arguments!</p>
  
  <pre><code> public delegate object GenericStaticInvoker(params object[] arguments);
  
   public static GenericStaticInvoker GenericMethodInvokerStaticMethod(Type type, string methodName, Type[] typeArguments, Type[] parameterTypes)
      {
          MethodInfo methodInfo;
          ParameterInfo[] parameters;
  
          // find the method to be invoked
          FindStaticMethod(type, methodName, typeArguments, parameterTypes, out methodInfo, out parameters);
  
          string name = string.Format("__MethodInvoker_{0}_ON_{1}", methodInfo.Name, methodInfo.DeclaringType.Name);
  
          DynamicMethod dynamicMethod;
          dynamicMethod = new DynamicMethod(name, typeof(object), new Type[] { typeof(object[]) }, methodInfo.DeclaringType);
  
          ILGenerator generator = dynamicMethod.GetILGenerator();
  
          // define local vars
          if (methodInfo.ReturnType != typeof(void))
              generator.DeclareLocal(methodInfo.ReturnType);
  
          for (int i = 0; i &lt; parameters.Length; i++)
          {
              // load paramters they are passed as an object array
              generator.Emit(OpCodes.Ldarg_1);
  
              // load array element
              generator.Emit(OpCodes.Ldc_I4, i);
              generator.Emit(OpCodes.Ldelem_Ref);
  
              // cast or unbox parameter as needed
              Type parameterType = parameters[i].ParameterType;
              if (parameterType.IsClass)
              {
                  generator.Emit(OpCodes.Castclass, parameterType);
              }
              else
              {
                  generator.Emit(OpCodes.Unbox_Any, parameterType);
              }
          }
  
          // call method
          generator.EmitCall(OpCodes.Call, methodInfo, null);
  
          // handle method return if needed
          if (methodInfo.ReturnType == typeof(void))
          {
              // return null
              generator.Emit(OpCodes.Ldnull);                
              generator.Emit(OpCodes.Ret);
          }
          else
          {
              // box value if needed
              if (methodInfo.ReturnType.IsValueType)
              {
                  generator.Emit(OpCodes.Box, methodInfo.ReturnType);
              }
  
              // store to the local var
              generator.Emit(OpCodes.Stloc_0);
  
              // load local and return
              generator.Emit(OpCodes.Ldloc_0);
              generator.Emit(OpCodes.Ret);
          }
  
  
  
          // return delegate
          return (GenericStaticInvoker)dynamicMethod.CreateDelegate(typeof(GenericStaticInvoker));
      }
  </code></pre>