title: What's the easiest way to generate code dynamically in .NET 4.5?
body: <p>I'm writing a specific kind of object-mapper. Basically I want to convert from a <code>DataTable</code> that has the fields <code>a</code>, <code>b</code> and <code>c</code> to an object that has properties <code>a</code>, <code>b</code> and <code>c</code> (the class of the object will be written by hand). There will be many different DataTables and many different classes that they will need to map to, so I want to make a generic mechanism that performs this data copying. Basically, I want the following function:</p>
  
  <pre><code>public T Map&lt;T&gt;(DataTable t) where T: new() { ... }
  </code></pre>
  
  <p>Now, I can do this with Reflection, but that's slow. This function will be at the core of the framework and will be used often. So I'm thinking about dynamic code generation. The first time this method is run on a specific <code>T</code> it will perform the necessary reflection and emit an anonymous method that does all the appropriate mapping. The next time it will just run that code. This should be as performant as possible.</p>
  
  <p>Just one problem - I've never emitted code at runtime. How do I do that? I looked at <code>Expressions</code>, but they can only do, well, expressions, not a series of statements.</p>
  
  <p>Then there's CodeDOM and <code>CSharpCodeProvider</code>. That sort of works - I can generate C# code as a string, compile it on-the-fly and then get a reference. However it involves the C# compiler and generates a whole new in-memory assembly. Sounds a bit... heavyweight for one simple method.</p>
  
  <p>Is there some simpler way? Something that generates a lightweight, anonymous method not attached to any assembly (or attached to an existing assembly)?</p>
  
  <hr>
  
  <p>OK, since people asked for an example.</p>
  
  <p>Here's a class, written by hand</p>
  
  <pre><code>class MyBusinessObject
  {
      public int a;
      public string b { get; set; }
  }
  </code></pre>
  
  <p>Here's a DataTable, prepared by hand (in real life, this will come from an external library):</p>
  
  <pre><code>DataTable t = new DataTable();
  t.AddColumn("a", typeof(int));
  t.AddColumn("b", typeof(string));
  t.AddRow(42, "Meaning");
  </code></pre>
  
  <p>Here's the method that should be generated on the fly:</p>
  
  <pre><code>(DataRow drow, MyBusinessObject o) =&gt;
  {
      o.a = (int)drow["a"];
      o.b = (string)drow["b"];
  }
  </code></pre>
  
  <p>I've omitted some other stuff I need for brevity, but that's the meat of the issue.</p>