title: Dynamically replace the contents of a C# method?
body: <p>What I want to do is change how a C# method executes when it is called, so that I can write something like this:</p>
  
  <pre><code>[Distributed]
  public DTask&lt;bool&gt; Solve(int n, DEvent&lt;bool&gt; callback)
  {
      for (int m = 2; m &lt; n - 1; m += 1)
          if (m % n == 0)
              return false;
      return true;
  }
  </code></pre>
  
  <p>At run-time, I need to be able to analyse methods that have the Distributed attribute (which I already can do) and then insert code before the body of the function executes and after the function returns.  More importantly, I need to be able to do it without modifying code where Solve is called or at the start of the function (at compile time; doing so at run-time is the objective).</p>
  
  <p>At the moment I have attempted this bit of code <em>(assume t is the type that Solve is stored in, and m is a MethodInfo of Solve)</em>:</p>
  
  <pre><code>private void WrapMethod(Type t, MethodInfo m)
  {
      // Generate ILasm for delegate.
      byte[] il = typeof(Dpm).GetMethod("ReplacedSolve").GetMethodBody().GetILAsByteArray();
  
      // Pin the bytes in the garbage collection.
      GCHandle h = GCHandle.Alloc((object)il, GCHandleType.Pinned);
      IntPtr addr = h.AddrOfPinnedObject();
      int size = il.Length;
  
      // Swap the method.
      MethodRental.SwapMethodBody(t, m.MetadataToken, addr, size, MethodRental.JitImmediate);
  }
  
  public DTask&lt;bool&gt; ReplacedSolve(int n, DEvent&lt;bool&gt; callback)
  {
      Console.WriteLine("This was executed instead!");
      return true;
  }
  </code></pre>
  
  <p>However, MethodRental.SwapMethodBody only works on dynamic modules; not those that have already been compiled and stored in the assembly.</p>
  
  <p>So I'm looking for a way to effectively do SwapMethodBody on a <strong>method that is already stored in a loaded and executing assembly</strong>.</p>
  
  <p>Note, it is not an issue if I have to completely copy the method into a dynamic module, but in this case I need to find a way to copy across the IL as well as update all of the calls to Solve() such that they would point to the new copy.</p>