<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://community.bartdesmet.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>B# .NET Blog</title><link>http://community.bartdesmet.net/blogs/bart/default.aspx</link><description>Bart De Smet&amp;#39;s on-line blog (0x2B | ~0x2B, that&amp;#39;s the question)</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Dude, Where’s My LINQ DML?</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/11/22/dude-where-s-my-linq-dml.aspx</link><pubDate>Sat, 22 Nov 2008 21:53:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14085</guid><dc:creator>bart</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14085</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/11/22/dude-where-s-my-linq-dml.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;On last week’s TechEd EMEA Developers 2008 conference in Spain I redelivered my talk on writing custom LINQ providers, showing off implementations of LINQ to AD and LINQ to SharePoint. One of the questions I received afterwards went along the lines of this blog post’s title: “Dude, where’s my LINQ DML statement support?”. The stock answer to this kind of question points out that it’s up to individual LINQ providers to &lt;em&gt;provide&lt;/em&gt; reasonable support for updating data source entries based on the O/whatever mapping they establish. The typical way this is done is through change tracking of entity objects that have been new’ed up by the provider upon execution of the query through LINQ.&lt;/p&gt;  &lt;p&gt;However, there are cases where this kind of updating is unsatisfactory, especially when dealing with batch updates that don’t require client-side input or computation. For example, when dealing with interactive users, the change tracking driven solution works great, but when updating a set op records based on a certain update pattern (e.g. increase the price of each product with 5%) there’s no need to suck in all entity objects from the data source only to send them back with updates that could well be executed by the target database. Obviously it all depends on the richness of the underlying database’s DML statements, but assuming it’s flexible enough, how to deal with this in the context of LINQ?&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Updateable LINQ to Objects&lt;/h1&gt;  &lt;p&gt;In order to set the scene, let’s investigate what it would take to make LINQ to Objects update-capable. In other words, we want to be able to execute a query and update the retrieved objects in a declarative fashion, i.e. without manual iteration over the query results. To tackle this problem, we can rely on extension methods over IEnumerable&amp;lt;T&amp;gt; in order to provide a method that can apply a certain update-action to each individual object in the sequence. Here’s a possible implementation.&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt;[] updates)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(source == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;source&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(updates == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;updates&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(T item &lt;span style="color:blue;"&gt;in &lt;/span&gt;source)
    {
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; update &lt;span style="color:blue;"&gt;in &lt;/span&gt;updates)
        {
            update(item);
        }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This particular implementation will break the IEnumerable&amp;lt;T&amp;gt; chain as the method is void-returning, but it’s not hard to make it an iterator, yield returning the original sequence elements from the outer loop after the updates have taken place. However, using an iterator in this case might not be the best idea, as the update won’t go through till you start iterating over the resulting sequence because of the lazy nature iterators have. So, let’s stick with void. Next, you might wonder why I chose to pass in an array of update actions instead of a just a single update action. It turns out this doesn’t really matter that much for the in-memory LINQ to Objects case (and indeed, if you just specify a single update action, it will just work fine) but as we’ll see further on, having more manageable individual update actions is a good idea to remote the DML statement. However, in this particular case there’s no way to have more control over the nature of updates, as an Action&amp;lt;T&amp;gt; can be used to point at any procedure, e.g. specified using a statement lambda. Below, I’m illustrating the use of the Update method with more granular update actions:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt; products = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt;() {
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Product &lt;/span&gt;{ Name = &lt;span style="color:#a31515;"&gt;&amp;quot;Chai&amp;quot;&lt;/span&gt;, Price = 123m },
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Product &lt;/span&gt;{ Name = &lt;span style="color:#a31515;"&gt;&amp;quot;Chang&amp;quot;&lt;/span&gt;, Price = 234m },
};

(&lt;span style="color:blue;"&gt;from &lt;/span&gt;p &lt;span style="color:blue;"&gt;in &lt;/span&gt;products
 &lt;span style="color:blue;"&gt;where &lt;/span&gt;p.Price &amp;gt; 100
 &lt;span style="color:blue;"&gt;select &lt;/span&gt;p).Update(
    p =&amp;gt; p.Price *= 0.95,
    p =&amp;gt; p.Name = p.Name.ToUpper()
);

&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;p &lt;span style="color:blue;"&gt;in &lt;/span&gt;products)
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(p.Name + &lt;span style="color:#a31515;"&gt;&amp;quot; - &amp;quot; &lt;/span&gt;+ p.Price);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Notice how other LINQ to Objects operators are used indirectly through query comprehension syntax, more specifically we filter out the items to be updated using a where clause first. As Update performs eager evaluation, enumerating over the source sequence straight away, the results will be visible immediately when iterating over the (now updated) source sequence after the Update invocation. But let’s take a closer look at how we’re specifying the updates above:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;p =&amp;gt; p.Price *= 0.95&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we’re using lambda syntax but notice how the specified lambda doesn’t have a statement body. We’re simply leveraging the fact any value can be ‘converted’ to void, so the lambda above which is of type Product –&amp;gt; decimal can be assigned to an Action&amp;lt;T&amp;gt; where T is Product or, in functional signature syntax, a Product –&amp;gt; void. But there’s nothing that keeps us from writing a far more complex statement body:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;p =&amp;gt; { 
      &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;decimal &lt;/font&gt;oldPrice = p.Price; 

      &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;string &lt;/font&gt;oldName = p.Name; 

      &lt;br /&gt;&amp;#160;&amp;#160; p.Price = oldPrice * 0.95; 

      &lt;br /&gt;&amp;#160;&amp;#160; p.Name = oldName.ToUpper(); 

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Just let your imagination work. Why is this a relevant fact? Our original set of update actions are far more “comprehensible” at runtime for introspection (well, if we turn them in something else than Action&amp;lt;T&amp;gt; which doesn’t produce just plain old IL code) because of their declarative nature.&lt;/p&gt;

&lt;p&gt;There are still quite a few things lacking from our simplistic LINQ to Objects update support mechanism, such as transactional integrity (e.g. assume one of the update actions blows up, how to roll back previous applied updates?) but you get the overall idea.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Updateable remotable LINQ&lt;/h1&gt;

&lt;p&gt;Now, let’s turn the scene and focus on remotable kinds of LINQ, where we want to send off the DML statement to a remote component, e.g. a DBMS system, to execute the update statement. In order to accomplish this goal, we need a way to represent the update statement in some form that we can inspect at runtime to cross-translate it into the remote DML language, e.g. SQL. Luckily we have such a capability in the framework today, with expression trees.&lt;/p&gt;

&lt;p&gt;But what’s in a name? Yes, &lt;em&gt;expression&lt;/em&gt; trees. So, we don’t have the ability to represent arbitrary pieces of procedural statement-driven code like we have above with Action&amp;lt;T&amp;gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; a = i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); }; &lt;font color="#008000"&gt;// works&lt;/font&gt; 

      &lt;br /&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; e = i =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i); } &lt;font color="#008000"&gt;// fails to compile&lt;/font&gt;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;On the one hand, this is a pity as it limits our expressiveness, but on the other hand it’s a good thing as analyzing arbitrary statement trees would significantly boost the complexity of the translator we’re about to write. However, there’s one significant limitation imposed by this: our update ‘actions’ cannot contain an assignment operator as this can’t be expressed by an expression tree:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;…&amp;gt; e = p =&amp;gt; p.Price *= 0.95;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;So, even if we’d find a way to specify expression trees to build up a DML statement (see further), we can’t make assignments which obviously is a pretty basic piece of functionality when dealing with updates. So, how to work around this? What about the following? Instead of representing an update ‘action’ as one function, we could represent it as two functions: one that acts as a “update target selector” denoting which entity property to update (e.g. p =&amp;gt; p.Price) and one that calculates the new value (e.g. p =&amp;gt; p.Price * 0.95). Together these two carry enough information to express the intent of the update:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;, &lt;span style="color:blue;"&gt;decimal&lt;/span&gt;&amp;gt;&amp;gt; extract = p =&amp;gt; p.Price;&lt;br /&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;, &lt;span style="color:blue;"&gt;decimal&lt;/span&gt;&amp;gt;&amp;gt; update = p =&amp;gt; p.Price * 0.95;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This is a little unfortunate and although there are alternatives (e.g. cooking up some “Updater” object that carries both extractor and updater) most of these yield syntactical clutter, so the bets of having a signature as easy as the following are off:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Using an Updater object, we’d end up with:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;T, R&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;but calling it would be cumbersome:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Update( 
      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;, &lt;font color="#0000ff"&gt;decimal&lt;/font&gt;&amp;gt;(p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95), 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt;(p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper()) 

      &lt;br /&gt;)&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;where Update has a constructor taking in:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Updater&lt;/font&gt;&amp;lt;T, R&amp;gt; 

      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;Updater(&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T,R&amp;gt;&amp;gt; extract, &lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T,R&amp;gt;&amp;gt; update)&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ideally, we’d have a way to use tuples to keep the two function expression trees together at all times, also being able to use them in a params:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;font color="#008080"&gt;Tuple&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, R&amp;gt;&amp;gt; &lt;font color="#008000"&gt;/* extract */&lt;/font&gt;, &lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, R&amp;gt;&amp;gt; &lt;font color="#008000"&gt;/* update */&lt;/font&gt;&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and hence the ability to call them easily using some hypothetical call-site syntax:&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;Update( 
    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95), 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper()) 

    &lt;br /&gt;)&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;or even without the additional parentheses pairs (at this time I’m even not thinking about disambiguation, overload resolution, betterness rules, and all this goodness). Or, we could lift the common Expression part out of the tuples, ending up with:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Update&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, &lt;font color="#008080"&gt;Tuple&lt;/font&gt;&amp;lt;R &lt;font color="#008000"&gt;/* extract */&lt;/font&gt;, R &lt;font color="#008000"&gt;/* update */&lt;/font&gt;&amp;gt;&amp;gt;&amp;gt;[] updates) &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Internally, the Update method could now inspect the way the Tuple&amp;lt;R,R&amp;gt; is instantiated, extracting the expression trees for the extract and update parts. However, we’re not all too pleased with the calling syntax that would need to new up tuple objects, obfuscating the intent of the code.&lt;/p&gt;

&lt;p&gt;Let’s go over our needs and observations one more time before we settle on some design:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;We’re bound to the limitations of expression trees; hence: 
    &lt;ul&gt;
      &lt;li&gt;we cannot express an individual update action as one expression (no assignment operation supported); &lt;/li&gt;

      &lt;li&gt;so, an update action needs to be split into an extract and update phase; &lt;/li&gt;

      &lt;li&gt;and, by extension, an update action can only target one value on the entity object at a time. &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;It should be possible to specify multiple update actions at a time to execute them as one unit: 
    &lt;ul&gt;
      &lt;li&gt;this supports transactional updates; &lt;/li&gt;

      &lt;li&gt;we need a way to batch up update actions. &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Introducing IUpdateable&amp;lt;T&amp;gt;&lt;/h1&gt;

&lt;p&gt;By now, we all know about the mysterious IQueryable&amp;lt;T&amp;gt; interface of LINQ. I’ve blogged about it several times, but here’s the key take-away: IQueryable&amp;lt;T&amp;gt; represents a query, wrapping an expression tree denoting the semantics of the intended query, and providing iteration facilities by means of its IEnumerable&amp;lt;T&amp;gt; parent. This, however, only tells half of the story, namely the “IQuery” part. The other half, the “able” part, is not visible on the interface per se, and allows users to extend the query by applying additional query operators that are supplied by means of the extension method in the Queryable class, each of which represents a query operator, like Where, Select, OrderBy, etc. This design allows the implementer of the interface to focus on the query execution part rather than the query construction part which is totally done on behalf of the implementer by means of the extension methods.&lt;/p&gt;

&lt;p&gt;One way to think about IQueryable&amp;lt;T&amp;gt; in general is as a giant state machine. Most of the IQueryable&amp;lt;T&amp;gt; extension methods return an IQueryable&amp;lt;T&amp;gt;, so applying the method (i.e. some query operator) puts us back in the domain of a (new) IQueryable&amp;lt;T&amp;gt;. However, there are other methods like AsEnumerable that allow us to switch to another world, the one of IEnumerable&amp;lt;T&amp;gt;, where we have similar extension methods. To provide update support, we can play a similar trick:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Users write the base query (typically only using filtering) to extract the records that need to be updated – this happens in the IQueryable&amp;lt;T&amp;gt; domain. &lt;/li&gt;

  &lt;li&gt;Next, we transition out of the IQueryable&amp;lt;T&amp;gt; into the IUpdateable&amp;lt;T&amp;gt; domain to provide update support. &lt;/li&gt;

  &lt;li&gt;In IUpdateable&amp;lt;T&amp;gt;, updates can be batched up by calls to a Set method, specifying individual update actions, returning a new IUpdateable&amp;lt;T&amp;gt;. &lt;/li&gt;

  &lt;li&gt;Once all update actions have been specified, an Update method can be called to execute the batch of updates. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A few questions and remarks:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Why starting for IQueryable&amp;lt;T&amp;gt;? In quite some cases, users will want to filter records before applying updates. Right, so what about just having a Where method on IUpdateable&amp;lt;T&amp;gt;? Well, it turns out other operators might be useful as well, such as ordering in case the update would be used to number items based on their ordering (left to the reader as an exercise to think about ways to provide this capability in IUpdateable&amp;lt;T&amp;gt;). Similarly, things like Take could be translated into TOP clauses to apply the update only to the first number of items. And so on. In the end, providing all IQueryable&amp;lt;T&amp;gt; operators first, allowing the user to transition into IUpdateable&amp;lt;T&amp;gt; seems beneficial although some operators likely don’t make much sense (like Select, which would result in updating a projection…). &lt;/li&gt;

  &lt;li&gt;How to iterate over the resulting records, after the update has been applied? This kind of combined approach seems attractive too, but we won’t go there in the scope of the blog post. However, providing this feature shouldn’t be too hard, by means of an AsQueryable method, or by making IUpdateable&amp;lt;T&amp;gt; also IEnumerable&amp;lt;T&amp;gt;, where an iteration triggers execution of the update followed by iteration over the original query that got captured by AsUpdateable originally. This too is left as an exercise for the reader. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Time to present our new interface:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Expression { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
    &lt;span style="color:#2b91af;"&gt;IUpdateProvider &lt;/span&gt;Provider { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;It pretty much follows the design of IQueryable&amp;lt;T&amp;gt; where the Expression property captures the expression tree for the update so far, and the Provider property is used by the extension methods to gain access to a factory method to new up new IUpdateable&amp;lt;T&amp;gt; objects:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateProvider
&lt;/span&gt;{
    &lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; CreateUpdate&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;expression);
    &lt;span style="color:blue;"&gt;int &lt;/span&gt;Update(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt; expression);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In addition, the provider supplies an Update method that will take in the constructed updateable object’s expression tree, carrying out the update and returning the number of affected records. This one can be compared to the Execute method on IQueryProvider. So, how to use those two interfaces now? All of the direct uses will be provided by means of extension methods:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Updateable
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; AsUpdateable&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IQueryable&lt;/span&gt;&amp;lt;T&amp;gt; source)
    {
        &lt;span style="color:#2b91af;"&gt;IUpdateProvider &lt;/span&gt;updateProvider = source.Provider &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateProvider&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(updateProvider == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Update operations not supported by this query provider.&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;updateProvider.CreateUpdate&amp;lt;T&amp;gt;(
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
                &lt;span style="color:blue;"&gt;null&lt;/span&gt;,
                ((&lt;span style="color:#2b91af;"&gt;MethodInfo&lt;/span&gt;)&lt;span style="color:#2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod()).MakeGenericMethod(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T)),
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] { source.Expression }
            )
        );
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; Set&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt;&amp;gt; extract, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt;&amp;gt; update)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Provider.CreateUpdate&amp;lt;T&amp;gt;(
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
                &lt;span style="color:blue;"&gt;null&lt;/span&gt;,
                ((&lt;span style="color:#2b91af;"&gt;MethodInfo&lt;/span&gt;)&lt;span style="color:#2b91af;"&gt;MethodBase&lt;/span&gt;.GetCurrentMethod()).MakeGenericMethod(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(R)),
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] { source.Expression, extract, update }
            )
        );
    }

    &lt;span style="color:blue;"&gt;public static int &lt;/span&gt;Update&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IUpdateable&lt;/span&gt;&amp;lt;T&amp;gt; updateable)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;updateable.Provider.Update(updateable.Expression);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Here the first method, AsUpdateable, captures an existing IQueryable&amp;lt;T&amp;gt; and checks whether its provider (of type IQueryProvider) supports updates. This piggybacking on top of the existing provider infrastructure is a good thing in general as implementers of an update-capable provider will need to talk to the query provider in order to translate the query portion of the update statement (e.g. a WHERE clause). Being the flip side of it, this means it’s not really possible to sprinkle update support on top of an existing query provider without modifying that provider. You could imagine an additional overload to AsUpdateable that takes in an IUpdateProvider object, and though this would work you’d end up implementing some of the query operators yourself again (e.g. to support filtering). If you know the original query provider’s concrete class and you know it exposes a way to take in an expression tree representing a query, getting back the translated query, there might be a way to avoid duplication (provided the target query language is compositional in nature):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;provider = (&lt;font color="#008080"&gt;SomeSqlQueryProvider&lt;/font&gt;)source.Provider; 

      &lt;br /&gt;&lt;font color="#0000ff"&gt;string &lt;/font&gt;sql = provider.GetSqlStatement(source); 

      &lt;br /&gt;… 

      &lt;br /&gt;&lt;font color="#0000ff"&gt;string &lt;/font&gt;update = &lt;font color="#800000"&gt;“UPDATE “&lt;/font&gt; + … + &lt;font color="#800000"&gt;“ FROM (“&lt;/font&gt; + sql + &lt;font color="#800000"&gt;“)”&lt;/font&gt;; &lt;font color="#008000"&gt;// pseudo-SQL&lt;/font&gt;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But let’s ignore this for now. Other than this, AsUpdateable is straightforward, it takes the original expression tree and wraps it in a MethodCallExpression for the current method. Just like IQueryable&amp;lt;T&amp;gt; does this, the original expression tree gets extended with information about the applied operators represented as method calls.&lt;/p&gt;

&lt;p&gt;The Set method, representing an individual update action, is completely similar. More interesting is its signature: besides of an IUpdateable&amp;lt;T&amp;gt; object, it takes in both the extract and update functions as expression trees, using the principle we talked about earlier.&lt;/p&gt;

&lt;p&gt;Finally, Update is just syntactical sugar on top of an IUpdateable&amp;lt;T&amp;gt; to call into the underlying provider to carry out the update, allowing for a fluent interface design. Ultimately, all of this can be used as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;(&lt;span style="color:blue;"&gt;from &lt;/span&gt;p &lt;span style="color:blue;"&gt;in new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Table&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt;()
 &lt;span style="color:blue;"&gt;where &lt;/span&gt;p.Price &amp;gt; 100
 &lt;span style="color:blue;"&gt;select &lt;/span&gt;p).AsUpdateable()
    .Set(p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95)
    .Set(p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper())&lt;br /&gt; .Update();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Going out in the woods we could start dreaming about integrated syntax that looks like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;from &lt;/span&gt;p &lt;span style="color:blue;"&gt;in new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Table&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Product&lt;/span&gt;&amp;gt;() 

      &lt;br /&gt;&lt;span style="color:blue;"&gt;where &lt;/span&gt;p.Price &amp;gt; 100 

      &lt;br /&gt;&lt;span style="color:blue;"&gt;update &lt;/span&gt;p.Price *= 0.95, 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; p.Name = p.Name.ToUpper();&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;which might automatically become eager, i.e. the Update call is implicit, or stays lazy (which would mean one can reuse the query/update comprehension expression). VB syntax could be very similar, optionally using the With keyword (Update p With …).&lt;/p&gt;

&lt;p&gt;Enough dreaming for now, this whole expression (more specifically everything before the .Update() part) translates into an expression tree, constructed at runtime with the aid of the Queryable query operators and Updateable update operators, that can be represented as follows using ToString notation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;expression = {value(Table`1[Product]).Where(p =&amp;gt; (p.Price &amp;gt; 100)).AsUpdateable().Set(p =&amp;gt; p.Price, p =&amp;gt; p.Price * 0.95).Set(p =&amp;gt; p.Name, p =&amp;gt; p.Name.ToUpper())}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now the update provider can go ahead and cross-translate this expression tree into a statement the target data source understands, e.g. a SQL DML statement for UPDATE (I’m not a SQL language expert, so treat the following as conceptual code):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;UPDATE &lt;/font&gt;Products &lt;font color="#0000ff"&gt;WHERE &lt;/font&gt;Price &amp;gt; 100 &lt;font color="#0000ff"&gt;SET &lt;/font&gt;Price *= 0.95, Name = &lt;font color="#0000ff"&gt;TOUPPER&lt;/font&gt;(Name)&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I’ll leave a concrete implementation of an update provider to the inspired reader; a basic prototype for SQL (only allowing columns to be updated with constant string or integer values) worked like a charm. In addition, the reader should feel free to think about how it would be possible (if desirable at all, something to think about as well) to make the “LINQ to Objects with update support” case similar to the remotable case, in terms of used operators (i.e. our current LINQ to Object implementation in the first paragraph doesn’t use Set method calls and isn’t lazy at all).&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=14085" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>Introducing “The C# Ducktaper” – Bridging the dynamic world with the static world</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/11/10/introducing-the-c-ducktaper-bridging-the-dynamic-world-with-the-static-world.aspx</link><pubDate>Mon, 10 Nov 2008 15:49:18 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14070</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14070</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/11/10/introducing-the-c-ducktaper-bridging-the-dynamic-world-with-the-static-world.aspx#comments</comments><description>&lt;h1&gt;Why this is not a C# 4.0 blog post…&lt;/h1&gt;  &lt;p&gt;By now most of you have probably heard about the &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/"&gt;dynamic capabilities&lt;/a&gt; that will be added to the C# 4.0 language. Search engines &lt;a href="http://search.live.com/results.aspx?q=c%23+4.0+dynamic&amp;amp;form=QBLH"&gt;start to fill&lt;/a&gt; their databases with lots of &lt;a href="http://blogs.msdn.com/cburrows/archive/tags/dynamic/default.aspx"&gt;descriptions of&lt;/a&gt; and discussions about the feature, but for now I won’t (yet) contribute to this (although at the time of fetching the previous link, my post on &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2006/11/23/DynCalc-_2D00_-Dynamic-Compilation-Illustrated-_2D00_-Part-4_3A00_-C_2300_-3.0-Expression-Trees.aspx"&gt;DynCalc&lt;/a&gt; was mistakenly on that list). Not yet, as it will get covered in my &lt;a href="http://bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx"&gt;C# 4.0 Feature Focus series&lt;/a&gt; in the foreseeable future, but let me give away my take on it:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;Today’s code is surrounded by an increasing number of dynamic environments and data sources. Targeting these is way too hard today. Think of interactions with JavaScript, loosely typed XML documents, calling into libraries written in dynamic languages, etc. It’s not because you’ve chosen for a statically typed environment like the CLR you should be punished when trying to reach out to any of these environments or data sources. So, dynamic is &lt;strong&gt;a good thing when used properly&lt;/strong&gt;, so the motto should be “static wherever possible, dynamic if necessary”.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So, what’s this post about then? To set the context for further posts on the C# 4.0 dynamic feature and other DLR related topics, I want to highlight a few basic principles of dynamic dispatching first. A while ago, in the context of framework testing frameworks and general DLR-related stuff, I came up with the (not so original) concept of a “ducktaper”. While it’s easy to reach out to a static world from within a dynamic fortress (e.g. PowerShell, IronRuby, IronPython, etc calling into BCL functionality) the reverse, &lt;strong&gt;calling dynamic objects as if they were static&lt;/strong&gt;, is like rowing against the current. The way people dealt with this problem for a long time is by creating statically typed wrappers around dynamic objects, which is a compile-time task as opposed to a runtime tasks. Doing this as a runtime task is what the “ducktaper” is all about.&lt;/p&gt;  &lt;p&gt;To wet your appetite, here’s what it’s meant to look like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;object&lt;/font&gt; dynamicDuck = GetDuckFrom(&lt;font color="#008080"&gt;DuckSource&lt;/font&gt;.Pond);         &lt;br /&gt;&lt;font color="#008080"&gt;IDuck &lt;/font&gt;duck = dynamicDuck.AsIf&amp;lt;&lt;font color="#008080"&gt;IDuck&lt;/font&gt;&amp;gt;();         &lt;br /&gt;duck.Walking += (o, e) =&amp;gt; { &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;“Duck is walking”&lt;/font&gt;); };         &lt;br /&gt;duck.Walk(); &lt;font color="#008000"&gt;// How can a static duck walk &amp;lt;g&amp;gt;?&lt;/font&gt;         &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(duck.Quack(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;));         &lt;br /&gt;duck.Walk();&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This post is not only about how to make such a thing work – and there are really a variety of ways to do this; I’ll only present the outcome of the last prototype – but also why this is or isn’t a good idea. Though I intend to keep this to one post (albeit a lengthy one I can already predict now), it might get a tail somehow :-). Notice &lt;strong&gt;no guarantees&lt;/strong&gt; are made about the code, use it at your own risk – it’s merely meant as a brain-dump on dynamic dispatching techniques.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;What’s in a name?&lt;/h1&gt;  &lt;p&gt;Well, two parts really: duck and tape. Etymological discussions don’t agree about the origin of the word “duct tape”, but duck is more appropriate in this context. A breakdown:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;duck&lt;/strong&gt; refers to “duck typing”, a programming language concept that allows developers to concentrate on the use of an object rather than its type. A typical way to refer to it is: “&lt;i&gt;If it walks like a duck and quacks like a duck, I would call it a duck.&lt;/i&gt;”, so as long as an object accepts (and responds to) Walk and Quack messages, we’re okay to send those messages.       &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;tape&lt;/strong&gt;, when applied, has the characteristic of putting pieces of stuff together. In this case we’re &lt;em&gt;binding&lt;/em&gt; dynamic objects to statically typed contracts, so you can consider it to be type-tape. The glue operator is called AsIf and will be described in a lengthy fashion in this post. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Where to get it?&lt;/h1&gt;  &lt;p&gt;With all the usual aforementioned &lt;strong&gt;&lt;font color="#ff0000"&gt;restrictions and warnings&lt;/font&gt;&lt;/strong&gt; applied, &lt;a href="http://www.bartdesmet.net/download/DuckTaper_Experimental_PublicRelease_v0.1.zip"&gt;here&lt;/a&gt;’s where you can grab the complete project, including:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Library code for the DuckTaper&lt;/li&gt;    &lt;li&gt;Sample use in a console application&lt;/li&gt;    &lt;li&gt;Unit tests&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The solution and projects are created in Visual Studio 2008. &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;How does it work?&lt;/h1&gt;  &lt;p&gt;Starting from a macroscopic level, let’s examine what the following call really looks like from the outside:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IDuck &lt;/font&gt;duck = dynamicDuck.AsIf&amp;lt;&lt;font color="#008080"&gt;IDuck&lt;/font&gt;&amp;gt;();       &lt;br /&gt;&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;The object on which we call AsIf&amp;lt;T&amp;gt; can be anything, so its type ought to be System.Object in order to yield this flexibility. As the System.Object type doesn’t have such a method, we need to cook our own (if it had such a method, this blog post wouldn’t have a reason to exist), so that’s where extension methods enter the picture. This is merely an implementation detail and I won’t even bother discussing whether or not it’s a good idea to put extension methods on the mother of all types (why not?), so I’ll leave the judgment to the reader. More relevant is the generic parameter that accepts an interface type, which becomes the return type. Putting the pieces together, we end up with this signature:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;T AsIf&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this object &lt;/span&gt;target) &lt;span style="color:blue;"&gt;where &lt;/span&gt;T : &lt;span style="color:blue;"&gt;class&lt;/span&gt;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Generic constraints (Partition II – 10.1.7) don’t have the expressive power to limit T to be an interface type, so we’ll need a runtime check as well. Our entry-point function ultimately looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;T AsIf&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this object &lt;/span&gt;target) &lt;span style="color:blue;"&gt;where &lt;/span&gt;T : &lt;span style="color:blue;"&gt;class
&lt;/span&gt;{
    &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;targetType = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T);

    &lt;span style="color:green;"&gt;//
    // Check target is an interface.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;if &lt;/span&gt;(!targetType.IsInterface)
        &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Target type of AsIf&amp;lt;T&amp;gt; cast should be an interface.&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;AsIfInternal&amp;lt;T&amp;gt;(target, targetType, &lt;span style="color:blue;"&gt;true&lt;/span&gt;);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;What’s behind the scenes in AsIfInternal will follow soon. But let’s elaborate on an important point here first: why does T need to be an interface? Ultimately what our implementation needs to do is generating an object type &lt;em&gt;at runtime&lt;/em&gt; that’s “compatible” with the type specified in generic parameter T. Allowing concrete types for T will make matters much more complicated, for lots of reasons (e.g. what if the type is sealed). But also from a philosophical point of view, we desire to “morph” the original object to a given &lt;em&gt;operational&lt;/em&gt; contract, so all we want here is some sort of (weak – to be explained below) contract that’s a description of the intended “interface” that’s to be layered on top of the existing object.&lt;/p&gt;

&lt;p&gt;For example, assume the retrieved duck object looks as follows (remember, for now we’re not considering arbitrary dynamic objects, so we’ll use plain C# class definition syntax here), omitting member definitions for clarity and brevity:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Duck
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Walk();
    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Walk(&lt;span style="color:blue;"&gt;int &lt;/span&gt;steps);
    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Quack(&lt;span style="color:blue;"&gt;object &lt;/span&gt;name);
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ConsoleColor &lt;/span&gt;Color { &lt;span style="color:blue;"&gt;get&lt;font color="#333333"&gt;; &lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;set&lt;font color="#333333"&gt;; }&lt;/font&gt;&lt;/span&gt;
    &lt;span style="color:blue;"&gt;public event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EventHandler &lt;/span&gt;Walking;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Next, consider the following desired “weak contract”:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;weak contract &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IDuck
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;void &lt;/span&gt;Walk();
    &lt;span style="color:blue;"&gt;void &lt;/span&gt;Walk(&lt;span style="color:blue;"&gt;int &lt;/span&gt;steps);
    &lt;span style="color:blue;"&gt;object &lt;/span&gt;Quack(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name);
    &lt;span style="color:#2b91af;"&gt;ConsoleColor &lt;/span&gt;Color { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EventHandler &lt;/span&gt;Walking;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Notice I’m not using the interface keyword above. We’re entering the realm of a hypothetical C# look-a-like. Going even further down the road of hypothetism, what we’re really looking for here is some kind of asif keyword that can “cast” an object to a weak contract, handing back a wrapper object that behaves like the contract but dispatches to the underling original object underneath:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IDuck &lt;/font&gt;duck = dynamicDuck &lt;font color="#0000ff"&gt;asif&lt;/font&gt; &lt;font color="#008080"&gt;IDuck&lt;/font&gt;;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;- or even -&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IDuck &lt;/font&gt;duck = dynamicDuck &lt;font color="#0000ff"&gt;asif&lt;/font&gt; { 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;void &lt;/span&gt;Walk(); 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;void &lt;/span&gt;Walk(&lt;span style="color:blue;"&gt;int &lt;/span&gt;steps); 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;object &lt;/span&gt;Quack(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name); 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:#2b91af;"&gt;ConsoleColor &lt;/span&gt;Color { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; } 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EventHandler &lt;/span&gt;Walking; 

      &lt;br /&gt;};&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;which is to be read as: “as if it were” or “as if it adhered to”. But why referring to this as a &lt;strong&gt;weak contract&lt;/strong&gt;? Interfaces, as we know them in C#, represent a strong contract. To the CLI, it doesn’t matter that much (Partition I – 8.2.3):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;A type fully describes a value if it unambiguously defines the value’s representation and the operations defined on that value. (…) Some types are only a partial description; for example, interface types. (…)&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The word contract doesn’t enter the picture here. However, languages like C# state things in a stronger manner (C# 3.0 specification, chapter 13):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;An interface describes a contract. A class or struct that implements an interface must adhere to its contract. (…)&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Both the provider of the interface and all of its consumers agree upon the contract and implementing an interface is like signing a strong &lt;u&gt;mutual&lt;/u&gt; contract. In here, the consumer agrees to adhere to the contract in its implementation, while the provider guarantees the contract is kept stable (with no room for small print). An interface embodies more than typing: interfaces often act as protocols between different parties, which are not expressible in the type system. For instance, the contract might require you to call Initialize first, followed by anything else as long as Dispose isn’t called. In practice this means interfaces cannot be changed, both on the type-level (messing with interface methods, adding/removing them, etc) and the semantic level. Changing stuff means creating a new interface – typically with a version number suffix – and having consumers sign the new contract.&lt;/p&gt;

&lt;p&gt;Why is this relevant in this context? Notice the Duck class above, it doesn’t implement IDuck (and assume IDuck is a &lt;u&gt;strong&lt;/u&gt; contract – i.e. an interface in realistic C# terms – for now) in an explicit manner. This means it’s not participating in the strong contract IDuck provides and we can only guess that the Duck object behaves like the IDuck specification. That’s what duck typing is about: the object looks like a duck, so there’s a &lt;em&gt;chance&lt;/em&gt; it’s really a duck. The hypothetical asif operator expresses taking the bet that the duck object really is a duck. In the sample case, the bet has little chances to be wrong, but &lt;strong&gt;we don’t have guarantees&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;To illustrate this, consider the following:&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;object&lt;/font&gt; dynamicDuck = GetDuckFrom(&lt;font color="#008080"&gt;DuckSource&lt;/font&gt;.&lt;font color="#ff0000"&gt;Oven&lt;/font&gt;); 

    &lt;br /&gt;&lt;font color="#008080"&gt;IDuck &lt;/font&gt;duck = dynamicDuck.AsIf&amp;lt;&lt;font color="#008080"&gt;IDuck&lt;/font&gt;&amp;gt;(); 

    &lt;br /&gt;duck.Walk();&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;Most likely a baked duck will throw a NotSupportedException (or a more &lt;em&gt;plastic&lt;/em&gt; exception type, depending on your imagination) when calling Walk, but what if IDuck assumes a living duck and doesn’t indicate NotSupportedException as a possible exception? Or what if the Quack method on IDuck specifies a specific duck language dialect to be spoken by the duck (although &lt;em&gt;that&lt;/em&gt; could be expressed in the type system)? The duck implementer did never explicitly say his duck implementation adheres to the rules of IDuck, and there can be a variety of reasons for this: maybe the implementer didn’t know about the IDuck interface, or maybe his duck isn’t compliant with the IDuck contract.&lt;/p&gt;

&lt;p&gt;Sometimes making a guess is relatively safe though. C# already does this to a limited extent:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;foreach only requires a GetEnumerator method to be present on the collection being iterated over; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://bartdesmet.net/blogs/bart/archive/2008/08/30/c-3-0-query-expression-translation-cheat-sheet.aspx"&gt;LINQ query comprehension keywords&lt;/a&gt; translate in method calls; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;both without a specific interface requirement. In the case of LINQ, requiring an interface to be used would result in a gigantic interface (containing all query operators) no-one would be interested in to implement (for more information on how to resolve this tension, see &lt;a href="http://bartdesmet.net/blogs/bart/archive/2008/08/15/the-most-funny-interface-of-the-year-iqueryable-lt-t-gt.aspx"&gt;The Most Funny Interface Of The Year … IQueryable&amp;lt;T&amp;gt;&lt;/a&gt;). Another place with similar flexibility rules is the &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2006/12/05/C_2300_-3.0-Feature-Focus-_2D00_-Part-3-_2D00_-Collection-Initializers.aspx"&gt;C# 3.0 collection initializers&lt;/a&gt; feature that require an Add method on an IEnumerable object (no, not an ICollection, this is not a typo – see paragraph 7.5.10.3 of the C# 3.0 specification).&lt;/p&gt;

&lt;p&gt;However, weak contracts are not a supported runtime or language construct at this point, so the best we can get is something that mimics a “collection of members” pretty well: interfaces. And this is an important caveat to point out: &lt;strong&gt;&lt;font color="#ff0000"&gt;we’re piggybacking on strong contracts to realize weak contracts, which is not ideal. &lt;/font&gt;&lt;/strong&gt;(It turns out it will get even a bit messier in the implementation in terms of visibility, see further…) Actually, we can put a band-aid mitigation in place as well, by sprinkling a custom attribute on interfaces indicating they’re used as a weak contract, and refusing to use any non-marked-as-such interfaces in the context of AsIf&amp;lt;T&amp;gt; (but as you realize, this is a uni-directional fix-up as it doesn’t avoid weak contracts to be used as a strong one). This strategy is implemented in the code that’s available for download:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;span style="color:blue;"&gt;&lt;font face="Courier New"&gt;weak contract &lt;/font&gt;&lt;/span&gt;&lt;font face="Courier New"&gt;&lt;span style="color:#2b91af;"&gt;IBar
        &lt;br /&gt;&lt;/span&gt;{

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;void &lt;/span&gt;Foo();

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;is indicated as&lt;/p&gt;

&lt;blockquote&gt;&lt;span style="color:blue;"&gt;&lt;font color="#000000"&gt;[&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;WeakContract&lt;/font&gt;]&lt;/font&gt;&lt;/font&gt;

    &lt;br /&gt;&lt;font face="Courier New"&gt;interface &lt;/font&gt;&lt;/span&gt;&lt;font face="Courier New"&gt;&lt;span style="color:#2b91af;"&gt;IBar
      &lt;br /&gt;&lt;/span&gt;{

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;void &lt;/span&gt;Foo();

    &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;How does it really work?&lt;/h1&gt;

&lt;p&gt;Now that we’ve pointed out a few important aspects of the implementation philosophy and restrictions imposed by the runtime and language concepts at hand, we can turn our attention to more implementation details. Our internal entry-point looks like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Creates a wrapper object of type &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparamref name=&amp;quot;T&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;T&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparamref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;around the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;object.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name=&amp;quot;T&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target type.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Object to be wrapped.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target type (avoids having to call typeof again).&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;shortCircuit&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Indicates whether or not short-circuiting is allows if the object already implements the specified interface.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Wrapper around the specified object.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
&lt;span style="color:blue;"&gt;private static &lt;/span&gt;T AsIfInternal&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;object &lt;/span&gt;target, &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;targetType, &lt;span style="color:blue;"&gt;bool &lt;/span&gt;shortCircuit) &lt;span style="color:blue;"&gt;where &lt;/span&gt;T : &lt;span style="color:blue;"&gt;class&lt;/span&gt;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;‘All’ we have to do in here is creating &lt;em&gt;something&lt;/em&gt; that looks like T while really acting as target. The first part of the equation translates into type generation, the second part into dispatching calls. Putting the pieces together we end up with &lt;strong&gt;type generation of a wrapper dispatching to the original object&lt;/strong&gt;. This is where System.Reflection.Emit kicks in. By itself this has a few caveats:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;A feature known as “restricted skip visibility” (see &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx"&gt;DynamicMethod&lt;/a&gt; on MSDN) is not available at this level, nor is it applicable (Why did I refer to it anyway? Well, because in philosophy it’s the same as what we need.) in our case. Since we’re implementing T (which, remember, denotes an interface type), what this really means is that the interface type should be public in order to have a dynamically emitted type in a dynamically emitted assembly implement it. &lt;/li&gt;

  &lt;li&gt;Loading a dynamically generated assembly into the current application domain makes it impossible to unload it; marshalling it across application domain boundaries would introduce its own set of problems. Actually the dynamic assembly (and module) is a side-effect of what we really need: just a dynamically generated type. On this field though, things will improve in .NET Framework 4.0 (but also for other reasons, making large parts of this blog post’s exercise &lt;em&gt;dispatchable&lt;/em&gt; to the CLR/DLR synergy). &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Remember this is a proof of concept implemented in today’s world of .NET, so we’ll ignore those issues for now. So, what are we up to? Some IL generation for sure, but let’s try to minimize the amount of IL that needs to be generated. As we’re wrapping an object – and not extending it in any way (for reasons outlined earlier) – we have the luxury to pull off a wrapper type that can derive from a base class. This has the additional benefit of having a way to determine statically whether an object is a dynamic object wrapper or not, by checking whether it derives from that particular wrapper base class (just an “is” or “as” suffices). Let us call this base class type Dynamic, then what we need to do translates into the following (in pseudo-meta-code):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#008080"&gt;&amp;lt;NameForTheWrapperObject&amp;gt;&lt;/font&gt; : &lt;font color="#008080"&gt;Dynamic&lt;/font&gt;, T 

    &lt;br /&gt;{ 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff8000"&gt;&amp;lt;%&lt;/font&gt; 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#008080"&gt;MemberInfo &lt;/font&gt;member &lt;font color="#0000ff"&gt;in typeof&lt;/font&gt;(T).GetMembers()) 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ImplementInterfaceMember(member); 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff8000"&gt;%&amp;gt;&lt;/font&gt; 

    &lt;br /&gt;}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The relevant piece here is the type hierarchy, creating a subtype of Dynamic while implementing interface T. Yet another reason why we need T to be an interface as multiple inheritance is banned from our world (for good enough reasons, but that’s a different discussion). A few remarks on this meta-code:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;GetMembers is considered to do a recursive scan of all members in the type hierarchy denoted by T. It’s possible that the interface T “inherits from” other interfaces, so we need to cover all members in the entire tree starting from T. &lt;/li&gt;

  &lt;li&gt;Interface members can be methods, properties, indexers (which are really a special kind of properties) and events. &lt;/li&gt;

  &lt;li&gt;Implementation of interface members will be the most complicated part obviously and will not only involve implementing the method with some stock code that does the dispatch but we’ll also need some fields to make everything work, see further. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But let’s start at the root: Dynamic. What does the Dynamic class need to be capable of doing? Here are its basic tasks:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It holds the wrapped object. &lt;/li&gt;

  &lt;li&gt;It has a way to dispatch invocations from the (to-be-implemented-by-subclass) interface members to the underlying wrapped objects. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To speed up dispatching we can introduce an intermediate concept that maintains a cache of possible invocation dispatch targets on a per-member basis. Doing so opens up for opportunities to provide fast paths when an invocation is repeated and have method overload resolution mechanisms decentralized from the wrapper object’s code and Dynamic base class’s code itself. Such a concept is often referred to as a “call site”, so let’s call that guy a CallSite. Although we won’t implement it in an advanced way, I still want to have it around to explain a few concepts. In fact you could well live without it, having the wrapper call into the base on some “InvokeMember” method that does the dispatch and implements caching strategies by itself. Here we enter the domain of what the DLR excels at, but we’ll avoid all of that complexity for the purposes of this blog post.&lt;/p&gt;

&lt;p&gt;Putting the pieces together, here’s what we end up with for Dynamic:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Base class for dynamic objects.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;public abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dynamic
&lt;/span&gt;{
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Target object.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;private object &lt;/span&gt;_target;

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Creates a new dynamic object wrapping the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target object&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Wrapped target object.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;protected &lt;/span&gt;Dynamic(&lt;span style="color:blue;"&gt;object &lt;/span&gt;target)
    {
        &lt;span style="color:blue;"&gt;this&lt;/span&gt;._target = target;
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Gets the wrapped target object.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public object &lt;/span&gt;Target
    {
        &lt;span style="color:blue;"&gt;get
        &lt;/span&gt;{
            &lt;span style="color:blue;"&gt;return &lt;/span&gt;_target;
        }
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Determines whether the wrapped object refers to the same object as the object wrapped by the passed in dynamic object.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;obj&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Object to compare to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;true if the wrapped object refers to the same object as the object wrapped by the passed in dynamic object; false otherwise.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
    /// &amp;lt;remarks&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Equality between a dynamic wrapped object and a non-wrapped object object always returns false as we can&amp;#39;t guarantee commutativity.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/remarks&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public override bool &lt;/span&gt;Equals(&lt;span style="color:blue;"&gt;object &lt;/span&gt;obj)
    {
        &lt;span style="color:#2b91af;"&gt;Dynamic &lt;/span&gt;dynamic = obj &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dynamic&lt;/span&gt;;

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(dynamic == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            &lt;span style="color:blue;"&gt;return false&lt;/span&gt;;

        &lt;span style="color:blue;"&gt;return object&lt;/span&gt;.ReferenceEquals(dynamic._target, &lt;span style="color:blue;"&gt;this&lt;/span&gt;._target);
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Returns the hash code of the wrapped object.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Hash code of the wrapped object.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public override int &lt;/span&gt;GetHashCode()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_target.GetHashCode();
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Returns the string representation of the wrapped object.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;String representation of the wrapped object.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;_target.ToString();
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Creates a call-site for the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;member&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;member&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;member&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Member to create a call-site for.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Call-site for the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;member&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;member&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;protected &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;CallSite &lt;/span&gt;GetCallSite(&lt;span style="color:blue;"&gt;string &lt;/span&gt;member)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;CallSite&lt;/span&gt;(&lt;span style="color:blue;"&gt;this&lt;/span&gt;._target, member);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Notice how Dynamic is a tiny wrapper around a System.Object instance also just forwarding methods like ToString and GetHashCode to the wrapped object. Equals is defined in terms of referential equality of the wrapped object too. Other than that, there are two pieces meant for use by the generated subclasses: the constructor (notice how the _target field is hidden from the subclasses – those subclasses don’t call into the Target getter either but you’ll have to take my word for it just for now) and the GetCallSite method.&lt;/p&gt;

&lt;p&gt;This GetCallSite method is of particular interest. The subtype of Dynamic will hold a CallSite field for every method implemented for the requested interface type. Notice I’m saying every &lt;em&gt;method&lt;/em&gt; which is not the same as every &lt;em&gt;member&lt;/em&gt;, because properties/indexers can have one or two methods (getter and/or setter) and so do events (add and/or remove methods). Those call site objects will be created lazily: on the first call to an implemented method, they are retrieved and stored in a private field. In other words, methods are resolved through call sites as they are called. This has pros and cons, which you can think about for a while (tip: early binding versus late binding; take the real dynamic nature of dynamic objects and &lt;em&gt;expandos&lt;/em&gt; into account as well). Time to move on to CallSite. As mentioned before this is really a rudimentary implementation and DLR / C# 4.0 mechanisms would be very appropriate here, which I’ll talk about another time:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Call site used to dispatch method calls on a thunk type instance to the underlying wrapped type.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;CallSite
&lt;/span&gt;{
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Object being wrapped by the thunk this call-site belongs to.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;private object &lt;/span&gt;_target;

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Name of the member to dispatch. CLI naming conventions are followed for special-name methods.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;private string &lt;/span&gt;_member;

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Creates a call-site to invoke the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;member&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;member&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;on the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target object&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target object to dispatch to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;member&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Member to invoke.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;CallSite(&lt;span style="color:blue;"&gt;object &lt;/span&gt;target, &lt;span style="color:blue;"&gt;string &lt;/span&gt;member)
    {
        _target = target;
        _member = member;
        Invoke = ResolveCall;
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Helper method to resolve a call the first time it&amp;#39;s made through the call-site.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;args&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Arguments to call the member with.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Return value from the dispatched call.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;private object &lt;/span&gt;ResolveCall(&lt;span style="color:blue;"&gt;object&lt;/span&gt;[] args)
    {
        &lt;span style="color:green;"&gt;//
        // TODO: Richer dispatching techniques, using DLR and C# 4.0 technologies.
        //

        //
        // Simplistic bind and invoke. Ideally we should call specialized binders here,
        // figure out whether the member is available and throw if it isn&amp;#39;t. Once we
        // have the target member, we can set up the fast path by overwriting Invoke.
        //
        &lt;/span&gt;Invoke = arguments =&amp;gt; _target.GetType().InvokeMember(_member, &lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.InvokeMethod, &lt;span style="color:blue;"&gt;null&lt;/span&gt;, _target, args, &lt;span style="color:#2b91af;"&gt;CultureInfo&lt;/span&gt;.InvariantCulture);

        &lt;span style="color:green;"&gt;//
        // First time call.
        //
        &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;Invoke(args);
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Invocation function used by the emitted code in the thunk to dispatch to the target method wrapped by this call-site.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;[], &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt; Invoke { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;One key concept is illustrated here: thunking. As the call site object is created, the Invoke member (which will be called by the emitted wrapper object, see further) is initially set to ResolveCall. When Invoke is called for the first time, the ResolveCall method it’s pointing at does all the (omitted/simplified in the code above) magic it needs to do in order to resolve the call (what’s in a name?), ultimately replacing Invoke by a new function that calls directly into the underlying member. Again there are pros and cons with regards to caching and the flexibility to do a re-resolve at a later time, so once more: this just illustrates one way of approaching things.&lt;/p&gt;

&lt;p&gt;Keep in mind where the CallSite corresponds to in the emitted object: an individual interface method implementation. This means the number of arguments passed in through the args array will always be the same, which is relevant for the call dispatch resolution as well since multiple overloads of the same method on the target interface will each have their own call site object. The way we solve the binding and dispatching here is in the most lame way imaginable: Type.InvokeMember with the default binder. More flexibility, including calling through expando objects, IDynamicObject, etc can be obtained by switching to DLR mechanics (with or without a different call site approach). Obviously you could experiment a little with your own logic in ResolveCall, for example to handle IExpando objects.&lt;/p&gt;

&lt;p&gt;Thunking is a technique used in a variety of places, including the CLR’s JIT infrastructure. The way it works there is as follows: upon loading an assembly and its types (assuming the non-ngen case), MethodTable structures in the EE will be filled with entries to a so-called pre-stub helper that invokes the JIT compiler for that method’s associated IL stream when called for the first time. The JIT compiler carries out IL-to-native translation, generating the native code on the heap and patching up the MethodTable entry with an address pointing at the start of the emitted native code. From that point on, for that method, the JIT compiler is out of the picture for the lifetime of the type in memory.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;How we cook our wrapper type&lt;/h1&gt;

&lt;p&gt;Now that we know the macroscopic structure, it’s time to dive into the microscopic world, and how better to start this than looking at what the emitted code should look like? Here’s the hypothetical target code, where the contract is really implemented as an interface of type IDuck:&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IDuck &lt;/font&gt;duck = dynamicDuck &lt;font color="#0000ff"&gt;asif&lt;/font&gt; { 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;void &lt;/span&gt;Walk(); 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;void &lt;/span&gt;Walk(&lt;span style="color:blue;"&gt;int &lt;/span&gt;steps); 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;object &lt;/span&gt;Quack(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name); 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:#2b91af;"&gt;ConsoleColor &lt;/span&gt;Color { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; } 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color:blue;"&gt;event &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EventHandler &lt;/span&gt;Walking; 

    &lt;br /&gt;};&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;Goal is to define the wrapper type now. We already reached an agreement on its type declaration before, i.e.:&lt;/p&gt;

&lt;blockquote&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#008080"&gt;&amp;lt;NameForTheWrapperObject&amp;gt;&lt;/font&gt; : &lt;font color="#008080"&gt;Dynamic&lt;/font&gt;, &lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IDuck 
      &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;{ 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff8000"&gt;&amp;lt;%&lt;/font&gt; 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#008080"&gt;MemberInfo &lt;/font&gt;member &lt;font color="#0000ff"&gt;in typeof&lt;/font&gt;(&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IDuck&lt;/font&gt;&lt;/font&gt;).GetMembers()) 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; ImplementInterfaceMember(member); 

  &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff8000"&gt;%&amp;gt;&lt;/font&gt; 

  &lt;br /&gt;}&lt;/blockquote&gt;

&lt;p&gt;Now what does an individual member of the interface look like? In this case IDuck stands by itself, so the call to GetMembers results in the degenerate case where no recursion is required, but in the general case we need recursion. Creating such a recursive method without getting stuck in cycles isn’t too hard, so let’s skip that technicality in this write-up as you can read the code yourself. What’s more interesting is how an individual interface member is implemented like. Starting with the base case of a method, here’s what we intend to do:&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;object &lt;/span&gt;Quack(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name); 

    &lt;br /&gt;&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;becomes&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:blue;"&gt;private &lt;font color="#008080"&gt;CallSite &lt;/font&gt;&lt;font color="#000000"&gt;_site1; 
          &lt;br /&gt;&lt;/font&gt;

        &lt;br /&gt;public object &lt;/span&gt;Quack(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name) 

      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(_site1 == &lt;font color="#0000ff"&gt;null&lt;/font&gt;) 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site1 = &lt;font color="#0000ff"&gt;base&lt;/font&gt;.GetCallSite(&lt;font color="#800000"&gt;“Walk”&lt;/font&gt;); 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;(&lt;font color="#0000ff"&gt;object&lt;/font&gt;)_site1.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[] { name }); 

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we make sure the field representing the call site for this particular method (overload) is initialized, followed by a call through the site’s Invoke delegate passing in all parameters as an object array and casting the return value back to the return type on the interface member (which turns out to be object anyhow).&lt;/p&gt;

&lt;p&gt;As we don’t have the compiler as a service just yet, we need to cook our own IL emission here, so this calls for System.Reflection.Emit magic. As we’re building a type we can’t get away with the DynamicMethod class, so we need to buy in to the entire stack of builder types that provide the chain of “assembly contains modules contains types contains members”. We can short-circuit stuff a bit by limiting ourselves to one assembly containing one module which will contain all the built wrapper types during the execution of the program (actually on a per appdomain level, but let’s ignore that for now).&lt;/p&gt;

&lt;p&gt;First we need to have all the machinery to ensure a singleton ModuleBuilder instance:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Ensures the module builder singleton is available.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static void &lt;/span&gt;EnsureModuleBuilder()
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(s_moduleBuilder == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    {
        &lt;span style="color:#2b91af;"&gt;AssemblyBuilder &lt;/span&gt;assemblyBuilder = &lt;span style="color:#2b91af;"&gt;AppDomain&lt;/span&gt;.CurrentDomain.DefineDynamicAssembly(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AssemblyName&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;DuckTaperGen&amp;quot;&lt;/span&gt;), &lt;span style="color:#2b91af;"&gt;AssemblyBuilderAccess&lt;/span&gt;.Run);
        s_moduleBuilder = assemblyBuilder.DefineDynamicModule(&lt;span style="color:#a31515;"&gt;&amp;quot;Thunks&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;One relevant thing here is the AssemblyBuilderAccess enum value passed in. We’ll only emit the assembly to run it in memory, but with RunAndSave we could save our thunk-types for reuse as well (I’m overloading the word “thunk” here to indicate a type that acts as a thunk around the wrapped object, feel free to substitute thunk with wrapper in what follows – with some goodwill, the thunking part of it is actually the fact it fills in call sites lazily). Now we have this, it’s time to new up the required TypeBuilder for our thunk type:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Gets a type builder for a type with the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;thunkTypeName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;type name&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;thunkTypeName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Name of the type to create a type builder for.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Type builder for the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;thunkTypeName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;name&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;GetTypeBuilder(&lt;span style="color:blue;"&gt;string &lt;/span&gt;thunkTypeName)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;s_moduleBuilder.DefineType(thunkTypeName, &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.Class | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.AutoLayout | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.AnsiClass | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.Sealed | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.BeforeFieldInit);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we follow the metadata flags used on classes emitted by the C# compiler, all of which you can find the meaning for in ECMA 335: public, sealed and class are straightforward, others have to do with the type layout, string treatment and initialization guarantees. How will we name our thunk type? It definitely needs to be unique and it’s auto-generated so let’s make it a little obscure:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Gets a unique name for the thunk created for the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target type&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target type to get a unique thunk type name for.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Thunk type name for the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target type&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static string &lt;/span&gt;GetThunkTypeName(&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;targetType)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#a31515;"&gt;&amp;quot;&amp;lt;&amp;gt;__Thunks.&amp;quot; &lt;/span&gt;+ targetType.FullName;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Remember the CLR doesn’t know about namespaces at all, so the FullName of the passed in type will contain the namespace as well as the prefix (looking as the top namespace), so we’re sure to have a unique name. Given those pieces of glue, we can start moving (back) on to the entry point and take it from there:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Creates a wrapper object of type &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;typeparamref name=&amp;quot;T&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;T&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparamref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;around the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;object.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name=&amp;quot;T&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target type.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name=&amp;quot;target&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Object to be wrapped.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target type (avoids having to call typeof again).&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;shortCircuit&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Indicates whether or not short-circuiting is allows if the object already implements the specified interface.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Wrapper around the specified object.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
&lt;/span&gt;[&lt;span style="color:#2b91af;"&gt;SuppressMessage&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Microsoft.Design&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;CA1004:GenericMethodsShouldProvideTypeParameter&amp;quot;&lt;/span&gt;, Justification = &lt;span style="color:#a31515;"&gt;&amp;quot;By design.&amp;quot;&lt;/span&gt;)]
&lt;span style="color:blue;"&gt;private static &lt;/span&gt;T AsIfInternal&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;object &lt;/span&gt;target, &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;targetType, &lt;span style="color:blue;"&gt;bool &lt;/span&gt;shortCircuit) &lt;span style="color:blue;"&gt;where &lt;/span&gt;T : &lt;span style="color:blue;"&gt;class
&lt;/span&gt;{
    &lt;span style="color:green;"&gt;//
    // Short-circuit objects that already implement the interface.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;if &lt;/span&gt;(shortCircuit)
    {
        T targetAsT = target &lt;span style="color:blue;"&gt;as &lt;/span&gt;T;
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(targetAsT != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            &lt;span style="color:blue;"&gt;return &lt;/span&gt;targetAsT;
    }

    &lt;span style="color:green;"&gt;//
    // Singleton module builder.
    //
    &lt;/span&gt;EnsureModuleBuilder();

    &lt;span style="color:green;"&gt;//
    // Get the thunk type.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;thunkType = GetThunk(targetType);

    &lt;span style="color:green;"&gt;//
    // Create and return the thunk instance.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;(T)&lt;span style="color:#2b91af;"&gt;Activator&lt;/span&gt;.CreateInstance(thunkType, target);
}

&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Gets the thunk type definition for the specified target type.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target type to get a thunk type definition for.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Thunk type definition for the specified target type.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
/// &amp;lt;remarks&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;If a thunk type has already been created for the target type, the same type definition will be returned.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/remarks&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;GetThunk(&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;targetType)
{
    &lt;span style="color:blue;"&gt;string &lt;/span&gt;thunkTypeName = GetThunkTypeName(targetType);

    &lt;span style="color:green;"&gt;//
    // Don&amp;#39;t regenerate the thunk type if it already exists for the specified target type.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;thunkType = s_moduleBuilder.GetType(thunkTypeName, &lt;span style="color:blue;"&gt;false&lt;/span&gt;, &lt;span style="color:blue;"&gt;false&lt;/span&gt;);
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(thunkType == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    {
        thunkType = BuildThunkType(targetType, thunkTypeName);
    }

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;thunkType;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Notice how we reuse thunk types in GetThunk if they were already created for the target interface. Thunk types are generic on a per-interface basis as their underlying code deals with a weakly typed object they dispatch to; the individual instances of the thunk type have the opportunity to diverge in terms of their generated call sites in order to provide the fastest possible dispatch to the underlying object for that object’s concrete runtime type. So, the type definition is the same, but the runtime instance can and will vary.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Builds a thunk type definition with the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;thunkTypeName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;name&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;for the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target type&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target type to create a thunk type definition for.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;thunkTypeName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Name to be used for the created thunk type definition.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Thunk type definition for the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;targetType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;target type&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;BuildThunkType(&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;targetType, &lt;span style="color:blue;"&gt;string &lt;/span&gt;thunkTypeName)
{
    &lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder = GetTypeBuilder(thunkTypeName);

    &lt;span style="color:green;"&gt;//
    // Set the parent type to Dynamic.
    //
    &lt;/span&gt;typeBuilder.SetParent(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Dynamic&lt;/span&gt;));

    &lt;span style="color:green;"&gt;//
    // Implement constructor for thunked object.
    //
    &lt;/span&gt;ImplementConstructor(typeBuilder);

    &lt;span style="color:green;"&gt;//
    // Implement all interfaces.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;int &lt;/span&gt;siteCounter = 0;
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;interfaceType &lt;span style="color:blue;"&gt;in &lt;/span&gt;GetInterfaces(targetType))
    {
        ImplementInterface(interfaceType, typeBuilder, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter);
    }

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;typeBuilder.CreateType();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In BuildThunkType we do the real work in case a thunk hasn’t been created yet. First we set the parent to be Dynamic, next we implement the constructor and finally we implement all interfaces specified by the target type, where we take the closure of all interfaces required. Skipping ImplementConstructor for a while (see next paragraph) and ignoring the recursive definition for GetInterfaces, here’s how ImplementInterface looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Implements the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;interfaceType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;interface type&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;interfaceType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Interface type to implement.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;typeBuilder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Type builder to emit to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;siteCounter&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Global counter for site fields used in the thunk type being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static void &lt;/span&gt;ImplementInterface(&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;interfaceType, &lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder, &lt;span style="color:blue;"&gt;ref int &lt;/span&gt;siteCounter)
{
    &lt;span style="color:green;"&gt;//
    // Add implements clause.
    //
    &lt;/span&gt;typeBuilder.AddInterfaceImplementation(interfaceType);

    &lt;span style="color:green;"&gt;//
    // Implement all members.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MemberInfo &lt;/span&gt;member &lt;span style="color:blue;"&gt;in &lt;/span&gt;interfaceType.GetMembers())
    {
        ImplementInterfaceMember(member, typeBuilder, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Besides the base class set through SetParent, all interfaces end up as base types (in CLI-style speak) and make up the type definition. For every to-be-implemented interface we finally implement every single member in it (otherwise the type would, naturally, be invalid and the CLR would refuse to new it up in the CreateType call). Notice the AddInterfaceImplementation will require the interface to be public as it will be part of another dynamically generated assembly, which is another limitation to our duck taper implementation, since such a weak contract interface is not really meant to be public in most circumstances. Oh well…&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Where IL generation kicks in&lt;/h1&gt;

&lt;p&gt;ImplementConstructor and ImplementInterfaceMember are the remaining pieces of code needed in order to make up the thunk type definition at runtime. The constructor is almost a triviality: simply call the base constructor on Dynamic and return:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Implements the constructor for a thunk type definition.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;typeBuilder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Type builder to emit to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static void &lt;/span&gt;ImplementConstructor(&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder)
{
    &lt;span style="color:green;"&gt;//
    // public &amp;lt;class&amp;gt;(object @object) : base(@object)
    // {
    // }
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ConstructorBuilder &lt;/span&gt;ctorBuilder = typeBuilder.DefineConstructor(&lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.HideBySig | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.SpecialName | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.RTSpecialName, &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.Standard, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] { &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;) });
    &lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ctorILGen = ctorBuilder.GetILGenerator();
    ctorILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg_0);
    ctorILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg_1);
    ctorILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Call, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Dynamic&lt;/span&gt;).GetConstructor(&lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.Instance | &lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.NonPublic, &lt;span style="color:blue;"&gt;null&lt;/span&gt;, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] { &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;) }, &lt;span style="color:blue;"&gt;null&lt;/span&gt;));
    ctorILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ret);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Recall the zero’th argument on an instance method represents the current instance, so Ldarg_1 and above fetch the real arguments. The base constructor we’re calling takes the same argument, i.e. the wrapped object. Ultimately, AsIf calls this constructor passing in the target object that needs to be AsIf’d:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color:green;"&gt;// 
        &lt;br /&gt;// Create and return the thunk instance. 

        &lt;br /&gt;// 

        &lt;br /&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;(T)&lt;span style="color:#2b91af;"&gt;Activator&lt;/span&gt;.CreateInstance(thunkType, target);&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now the real work: ImplementInterfaceMember. Here we dispatch based on the type of the member to be implemented:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Implements the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;member&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;interface member&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;member&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Member to generate an implementation for.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;typeBuilder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Type builder to emit to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;siteCounter&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Global counter for site fields used in the thunk type being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static void &lt;/span&gt;ImplementInterfaceMember(&lt;span style="color:#2b91af;"&gt;MemberInfo &lt;/span&gt;member, &lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder, &lt;span style="color:blue;"&gt;ref int &lt;/span&gt;siteCounter)
{
    &lt;span style="color:blue;"&gt;switch &lt;/span&gt;(member.MemberType)
    {
        &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemberTypes&lt;/span&gt;.Method:
            ImplementInterfaceMethod(member &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodInfo&lt;/span&gt;, typeBuilder, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter);
            &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemberTypes&lt;/span&gt;.Property:
            ImplementInterfaceProperty(member &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PropertyInfo&lt;/span&gt;, typeBuilder, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter);
            &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemberTypes&lt;/span&gt;.Event:
            ImplementInterfaceEvent(member &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EventInfo&lt;/span&gt;, typeBuilder, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter);
            &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;case &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemberTypes&lt;/span&gt;.NestedType:
            &lt;span style="color:green;"&gt;//
            // Nested interfaces are supported in VB. We ignore the nested interfaces and just implement the top-level interface.
            // This is fine as the nested interface isn&amp;#39;t really part of the outer contract (and not an implementation requirement
            // in terms of CLI), but is merely a syntactic convenience method to structure types that belong together.
            //
            &lt;/span&gt;&lt;span style="color:blue;"&gt;break&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;default&lt;/span&gt;:
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Unexpected interface member type encountered: &amp;quot; &lt;/span&gt;+ member.MemberType);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;I won’t cover all of the three member types individually here. The key take-away is that all are implemented very similarly and ultimately resort to the implementation of methods (properties have getters and setters, events have adders and removers), all of which are the same:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;A call site field. &lt;/li&gt;

  &lt;li&gt;Code to ensure the call site field is initialized (lazy on-demand call site creation) and to call through it. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;How to dispatch calls?&lt;/h1&gt;

&lt;p&gt;The code to dispatch a call isn’t that hard either, but let’s introduce it piece-meal:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Emits a thunk method with the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;methodName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;name&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;, &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;parameterTypes&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;parameter types&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;and &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;returnType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;return type&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;typeBuilder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Type builder to emit to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;methodName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Name for the generated method.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;parameterTypes&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Parameter types for the generated method, or an empty array for no parameters.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;returnType&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Return type for the generated method. Use typeof(void) for a void-returning method.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;targetMethodName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target method name to call on the object being thunked.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;siteCounter&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Global counter for site fields used in the thunk type being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;specialName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Indicates whether or not the emitted method should be marked as a special name method. Used for properties and events.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Method builder for the generated method.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodBuilder &lt;/span&gt;EmitMethod(&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder, &lt;span style="color:blue;"&gt;string &lt;/span&gt;methodName, &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] parameterTypes, &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;returnType, &lt;span style="color:blue;"&gt;string &lt;/span&gt;targetMethodName, &lt;span style="color:blue;"&gt;ref int &lt;/span&gt;siteCounter, &lt;span style="color:blue;"&gt;bool &lt;/span&gt;specialName)
{
    &lt;span style="color:green;"&gt;//
    // Method attributes.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodAttributes &lt;/span&gt;attributes = &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.HideBySig | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.NewSlot | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Virtual | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Final;
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(specialName)
        attributes |= &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.SpecialName;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Notice draw the distinction between method name and target method name. The former is the one that needs to be implemented on the generated thunk, i.e. the one used in the interface, while the latter denotes the target to call on the wrapped object. This opens up for the possibility to have target method mappings using custom attribute metadata:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IFoo
&lt;/span&gt;{
    [&lt;span style="color:#2b91af;"&gt;TargetMember&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Fo&amp;quot;&lt;/span&gt;)]
    &lt;span style="color:blue;"&gt;int &lt;/span&gt;Foo { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;I won’t elaborate on this mechanism as it’s pretty straightforward to implement, refer to the code for more information. Back to our EmitMethod definition, focusing on a few remaining interesting arguments:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;siteCounter is used to number the call site fields on the thunk type; as all our methods here are static we’re threading this around (an attractive alternative in case we’d have more state to drag around would be to have a ThunkBuilder class); &lt;/li&gt;

  &lt;li&gt;specialName is set to true for “special name methods” such as getters, setters, adders and removers. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Other metadata flags have to do with the vtable dispatching (NewSlot, Virtual) and such. Again, for more information, refer to the CLI spec ECMA 335. Now we start to build the real code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// Define the method.
//
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodBuilder &lt;/span&gt;methodBuilder = typeBuilder.DefineMethod(methodName, attributes, &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.HasThis, returnType, parameterTypes);
&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;methodILGen = methodBuilder.GetILGenerator();

&lt;span style="color:green;"&gt;//
// Get method header to retrieve a reference to the call-site for this method.
//
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FieldBuilder &lt;/span&gt;callSiteField = EmitGetCallSite(typeBuilder, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter, targetMethodName, methodILGen);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;First we declare the method, with HasThis calling convention (we’re writing an instance method, so the first argument is to be treated as “this”) and the indicated signature. The first thing we do is emitting the code responsible to ensure the call site object is not null and to create the backing field for it. First the field generation:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Declares a call-site field associated with the target interface method and emits the code for retrieval of the call-site field in the method being generated.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;typeBuilder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Type builder to emit to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;siteCounter&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Global counter for site fields used in the thunk type being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;targetMethodName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Target method name for the method to dispatch to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;methodILGen&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;IL generator for the method being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Field builder for the emitted call-site field.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FieldBuilder &lt;/span&gt;EmitGetCallSite(&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder, &lt;span style="color:blue;"&gt;ref int &lt;/span&gt;siteCounter, &lt;span style="color:blue;"&gt;string &lt;/span&gt;targetMethodName, &lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;methodILGen)
{
    &lt;span style="color:green;"&gt;//
    // Add call-site field.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FieldBuilder &lt;/span&gt;callSiteField = GetNewCallSiteField(typeBuilder, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter);

    &lt;span style="color:green;"&gt;//
    // Ensure the call-site is initialized.
    //
    &lt;/span&gt;EmitCallSiteNullCheckAndInit(callSiteField, targetMethodName, methodILGen);

    &lt;span style="color:green;"&gt;//
    // Return field for further reference.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;callSiteField;
}&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Defines a new call-site field.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;typeBuilder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Type builder to emit to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;siteCounter&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Global counter for site fields used in the thunk type being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;New call-site field.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FieldBuilder &lt;/span&gt;GetNewCallSiteField(&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder, &lt;span style="color:blue;"&gt;ref int &lt;/span&gt;siteCounter)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;typeBuilder.DefineField(&lt;span style="color:#a31515;"&gt;&amp;quot;_site&amp;quot; &lt;/span&gt;+ (++siteCounter), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;CallSite&lt;/span&gt;), &lt;span style="color:#2b91af;"&gt;FieldAttributes&lt;/span&gt;.Private);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Here we add a field to our type and increment our global site counter. Now we can refer to it in our method to ensure the field is initialized before calling the Invoke delegate:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Emits code to populate the specified &lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;paramref name=&amp;quot;callSiteField&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;call-site field&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/paramref&amp;gt; &lt;/span&gt;&lt;span style="color:green;"&gt;(if not done already) and to retrieve it.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;callSiteField&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Call-site field to populate and retrieve.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;methodName&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Name for the method being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;methodILGen&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;IL generator for the method being generated.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;private static void &lt;/span&gt;EmitCallSiteNullCheckAndInit(&lt;span style="color:#2b91af;"&gt;FieldBuilder &lt;/span&gt;callSiteField, &lt;span style="color:blue;"&gt;string &lt;/span&gt;methodName, &lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;methodILGen)
{
    &lt;span style="color:green;"&gt;//
    // if (&amp;lt;callSiteField&amp;gt; == null)
    //     &amp;lt;callSiteField&amp;gt; = base.GetCallSite(&amp;lt;methodName&amp;gt;);
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Label &lt;/span&gt;makeCall = methodILGen.DefineLabel();
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg_0);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldfld, callSiteField);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Brtrue, makeCall);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg_0);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg_0);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldstr, methodName);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Call, &lt