title: How to mutate a boxed struct using IL
body: <p>Imagine we have a mutable <code>struct</code> (yes, don't start):</p>
  
  <pre><code>public struct MutableStruct
  {
      public int Foo { get; set; }
      public override string ToString()
      {
          return Foo.ToString();
      }
  }
  </code></pre>
  
  <p>Using reflection, we can take a boxed instance of this <code>struct</code> and mutate it inside the box:</p>
  
  <pre><code>// this is basically what we want to emulate
  object obj = new MutableStruct { Foo = 123 };
  obj.GetType().GetProperty("Foo").SetValue(obj, 456);
  System.Console.WriteLine(obj); // "456"
  </code></pre>
  
  <p>What I would <em>like</em> to do is to write some IL that can do the same as this - but faster. I'm a meta-programming junkie ;p</p>
  
  <p>It is trivial to unbox-any the value and mutate the value using regular IL - but you can't just call box it afterwards because that will create a <strong>different</strong> box. I'm <em>guessing</em> that what we would need to do here is copy it over the existing box. I have investigated <code>ldobj</code> / <code>stobj</code>, but those don't seem to do the job (unless I'm missing something).</p>
  
  <p>So: does a mechanism to do this exist? Or must I limit myself to reflection to perform in-place updates of boxed <code>struct</code>s ?</p>
  
  <p>Or in other words: what <code>... evil goes here...</code> ?</p>
  
  <pre><code>var method = new DynamicMethod("evil", null,
      new[] { typeof(object), typeof(object) });
  var il = method.GetILGenerator();
  // ... evil goes here...
  il.Emit(OpCodes.Ret);
  
  Action&lt;object, object&gt; action = (Action&lt;object, object&gt;)
      method.CreateDelegate(typeof(Action&lt;object, object&gt;));
  action(obj, 789);
  System.Console.WriteLine(obj); // "789"
  </code></pre>