title: Calling A Method That Was Just Created. Error Calculating Max Stack Value
body: <p>so I was fooling around with DNLIB recently, and I was trying to add methods to a .net file. I got the methods from a previously compiled file, so basically, I was trying to mimic the method. </p>
  
  <p>There are 3 methods: GetTheTypes, InvokeIt, and InvokeCall.</p>
  
  <p>Firstly, I had to create the methods GetTheTypes and InvokeIt because InvokeCall calls both the GetTheTypes method and the InvokeIt method. So I added those methods, and they were added perfectly. It compiled and saved, and I was able to see them in a reflector/ILSpy with no problem. Note: when I add the methods, I have a check to see if they should be static or non-static, so that is not an issue. They are also all public methods.</p>
  
  <p>Then, I wanted to add the InvokeCall method. So I did the same thing I did for the other methods, opened the methods I wanted mimicked in ILSpy, then basically copied all of the instructions and local variables into a new CilBody which were added to the InvokeCall method that I was mimicking. The only problem was it threw an error saying <strong>"Error Calculating Max Stack Value"</strong>. The weird thing was, if I changed the OPCode from Call to NewObj, it compiled fine. But that is not what I want to do. What I want to do throws the error mentioned above.</p>
  
  <p>Here is the code I use to add the instruction:</p>
  
  <pre><code>cBody.Instructions.Add(OpCodes.Call.ToInstruction(_getTheTypesMethod))
  </code></pre>
  
  <p>The <strong>_getThetypesMethod</strong> variable is defined as a <strong>MethodDefUser</strong> and consists of the method I created ealier and compiled just fine. I have also tried this:</p>
  
  <pre><code>cBody.Instructions.Add(OpCodes.Call.ToInstruction(t.Asm.Import(_getTheTypesMethod)))
  </code></pre>
  
  <p>That also did not work. I have also tried to get the DeclaringType of the method as well, then Finding the method like this:</p>
  
  <pre><code>cBody.Instructions.Add(OpCodes.Call.ToInstruction(t.Asm.Import(_getTheTypesMethod.GetDeclaringType().FindMethod("GetTheTypes")))
  </code></pre>
  
  <p>That didn't work either. </p>
  
  <p>So if anyone has any suggestions as to how to call a method that was just created, please tell me. I've been trying to find out how to fix this problem for the last day or so, with no prevail. Thanks.</p>