title: How to create a dynamic method in C# which uses an "in" parameter?
body: <p>I try to create a dynamic method in .NET which has an &quot;in&quot; parameter, but it throws an exception in the <code>EmitCall</code> line:</p>
  <pre><code>public struct Context
  {
      public string MyString { get; set; }
  }
  
  public interface IHandler&lt;T&gt;
  {
      void MyMethod(in Context context);
  }
  
  class MyMessage
  {
  }
  
  class MyClass : IHandler&lt;MyMessage&gt;
  {
      public void MyMethod(in Context context)
      {
      }
  }
  
  class ContextMethodInvoker
  {
      private readonly InvokeHandler _invoker;
  
      private delegate void InvokeHandler(object handler, in Context context);
  
      public ContextMethodInvoker(MethodInfo methodInfo)
      {
          var dynamicMethod = new DynamicMethod(string.Empty,
              typeof(void), new[] { typeof(object), typeof(Context).MakeByRefType() });
          dynamicMethod.DefineParameter(1, ParameterAttributes.None, &quot;handler&quot;);
          dynamicMethod.DefineParameter(2, ParameterAttributes.In, &quot;context&quot;);
  
          var il = dynamicMethod.GetILGenerator();
          il.Emit(OpCodes.Ldarg_0);
          il.Emit(OpCodes.Ldarg_1);
  
          il.EmitCall(OpCodes.Callvirt, methodInfo, null);
          il.Emit(OpCodes.Ret);
  
          _invoker = (InvokeHandler)dynamicMethod.CreateDelegate(typeof(InvokeHandler));
      }
  
      public void Invoke(object handler, in Context context)
      {
          _invoker.Invoke(handler, in context);
      }
  }
  </code></pre>
  <p>And:</p>
  <pre><code>var messageHandlerType = typeof(IHandler&lt;&gt;);
  var messageType = typeof(MyMessage);
  var type = typeof(MyClass);
  
  var interfaceType = messageHandlerType.MakeGenericType(messageType);
  
   
  var contextMethod = new ContextMethodInvoker(
      type.GetInterfaceMap(interfaceType).TargetMethods.SingleOrDefault()
  );
  
  var tm = new Context
  {
      MyString = &quot;test&quot;
  };
  contextMethod.Invoke(Activator.CreateInstance(type), tm);
  </code></pre>
  <p>What am I doing wrong? When I remove the &quot;in&quot; keywords and the MakeByRefType then it works.</p>