<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.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 : Dynamic languages</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx</link><description>Tags: Dynamic languages</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Extension methods ain't Trojan horses – A tale on a covariant city built in and protected by C# 4.0</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2009/10/23/extension-methods-ain-t-trojan-horses-a-tale-on-a-covariant-city-built-in-and-protected-by-c-4-0.aspx</link><pubDate>Fri, 23 Oct 2009 07:06:44 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14848</guid><dc:creator>bart</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14848</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2009/10/23/extension-methods-ain-t-trojan-horses-a-tale-on-a-covariant-city-built-in-and-protected-by-c-4-0.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;Today, a colleague and I were playing with new C# 4.0 and BCL 4.0 features, me trying (and succeeding I think) to convince my co-worker about the merits of LINQ and its peripheral technologies. Users of Visual Studio 2010 Beta 2 may have noticed the new IObservable&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; interfaces in the System namespace:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;namespace &lt;/span&gt;System
{
    &lt;span style="color:green;"&gt;// Summary:
    //     Defines a provider for push-based notification.
    //
    // Type parameters:
    //   T:
    //     The object that provides notification information.This type parameter is
    //     covariant. That is, you can use either the type you specified or any type
    //     that is more derived. For more information about covariance and contravariance,
    //     see Covariance and Contravariance in Generics.
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;out &lt;/span&gt;T&amp;gt;
    {
        &lt;span style="color:green;"&gt;// Summary:
        //     Notifies the provider that an observer is to receive notifications.
        //
        // Parameters:
        //   observer:
        //     The object that is to receive notifications.
        //
        // Returns:
        //     The observer&amp;#39;s interface that enables resources to be disposed.
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable &lt;/span&gt;Subscribe(&lt;span style="color:#2b91af;"&gt;IObserver&lt;/span&gt;&amp;lt;T&amp;gt; observer);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    &lt;span style="color:green;"&gt;// Summary:
    //     Provides a mechanism for receiving push-based notifications.
    //
    // Type parameters:
    //   T:
    //     The object that provides notification information.This type parameter is
    //     contravariant. That is, you can use either the type you specified or any
    //     type that is less derived. For more information about covariance and contravariance,
    //     see Covariance and Contravariance in Generics.
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObserver&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;in &lt;/span&gt;T&amp;gt;
    {
        &lt;span style="color:green;"&gt;// Summary:
        //     Notifies the observer that the provider has finished sending push-based notifications.
        &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;OnCompleted();
        &lt;span style="color:green;"&gt;//
        // Summary:
        //     Notifies the observer that the provider has experienced an error condition.
        //
        // Parameters:
        //   error:
        //     An object that provides additional information about the error.
        &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;OnError(&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;error);
        &lt;span style="color:green;"&gt;//
        // Summary:
        //     Provides the observer with new data.
        //
        // Parameters:
        //   value:
        //     The current notification information.
        &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;OnNext(T value);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Those interfaces deserve whole blog series of their own (I promise to do so, some day) and have to do with the Reactive Framework discussed on various occasions on Channel 9:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx)&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://channel9.msdn.com/shows/Going+Deep/E2E-Erik-Meijer-and-Wes-Dyer-Reactive-Framework-Rx-Under-the-Hood-1-of-2/"&gt;E2E: Erik Meijer and Wes Dyer - Reactive Framework (Rx) Under the Hood 1 of 2&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://channel9.msdn.com/shows/Going+Deep/E2E-Erik-Meijer-and-Wes-Dyer-Reactive-Framework-Rx-Under-the-Hood-2-of-2/"&gt;E2E: Erik Meijer and Wes Dyer - Reactive Framework (Rx) Under the Hood 2 of 2&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;More info on this will appear on Channel 9 in the foreseeable future (stay tuned; I’ll be there!) but all that matters in the scope of this post is the use of two interesting keywords in the interface definitions above:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;out &lt;/span&gt;T&amp;gt; { … }

    &lt;br /&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObserver&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;in &lt;/span&gt;T&amp;gt; { … }&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Did you see them? The reuse of keywords out and in as modifiers on generic type parameters is what’s referred to as the new C# 4.0 feature called &lt;strong&gt;definition-site generic co- and contravariance for interface and delegate types&lt;/strong&gt;, or generic co- and contravariance for short. I’ve written about this in the past, explaining the concept in terms of apples of tomatoes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://bartdesmet.net/blogs/bart/archive/2009/04/15/14377.aspx#14401"&gt;C# 4.0 Feature Focus – Part 4 – Co- and Contra-Variance for Generic Delegate and Interface Types&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you don’t know about this stuff just yet, take a break and visit the link above before returning back here. The nice thing about all of this is that &lt;strong&gt;as a user of generic types declared to be co- and/or contravariant in certain type parameters, you don’t need to worry about it at all&lt;/strong&gt;. In fact, this feature allows you to write things you couldn’t write before:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Apple&lt;/span&gt;&amp;gt; apples = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;
&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Fruit&lt;/span&gt;&amp;gt; fruits = apples; &lt;span style="color:green;"&gt;// didn&amp;#39;t compile before!&lt;/span&gt;&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;But in .NET 4.0 with C# 4.0 and VB 10.0, you can. The point of variance annotations on generic type parameters is to make such operations provably, at compile-time, safe. Before this new language-level feature, generics were always &lt;strong&gt;invariant&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;An observed problem?&lt;/h1&gt;

&lt;p&gt;Loaded with my knowledge of generic co- and contravariance, I was surprised to see the following code compile fine. To be honest, the real scenario was more contrived than the simplified one below, with many intermediate types in the picture:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// When apples are thrown at us, we&amp;#39;ll write them to the screen.
// We don&amp;#39;t expect to see other fruits here!
//
// Note: This uses an extension method on IObservable&amp;lt;T&amp;gt; that
//       hides the declaration of an IObserver&amp;lt;T&amp;gt;. C# doesn&amp;#39;t
//       have anonymous inner types unfortunately...
//
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Apple&lt;/span&gt;&amp;gt; apples = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AngryAppleThrower&lt;/span&gt;();
apples.Subscribe(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);

&lt;span style="color:green;"&gt;//
// Fine, since IObservable&amp;lt;T&amp;gt; is covariant in T.
//
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Fruit&lt;/span&gt;&amp;gt; fruits = apples;

&lt;span style="color:green;"&gt;//
// What? A Banana is injected into an observable of Fruits?
// Though you may think this is fine, how will the observer
// above, expecting Apple objects, react to seeing a Banana?
// This is not type-safe; covariance should prevent this!
//
&lt;/span&gt;fruits.Inject(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Banana&lt;/span&gt;());&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;It just couldn’t be true that you could somehow sneak a Banana in an observable of Apple objects. That’s the whole point of type safety guarantees provided by co- and contravariance on generic types in C# 4.0.&amp;#160; I tried a few things to verify we could really pass subtypes of Fruit into the IObservable&amp;lt;T&amp;gt;. The following didn’t compile while the Banana-case did:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;fruits.Inject(&lt;span style="color:blue;"&gt;new string&lt;/span&gt;());&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Just looking at the sample above you can already smell what’s going on, maybe? Tip: look at the types of the variables. What letter do they start with? Then, where does Inject come from? If you don’t see it yet, don’t worry as I’ll reveal the answers in a second. Either way, I started to repro the above with simpler fictional types:&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;IO&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;out &lt;/span&gt;T&amp;gt;
{
}

&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IMyIO&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;out &lt;/span&gt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;IO&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;void &lt;/span&gt;Inject&amp;lt;S&amp;gt;(S s) &lt;span style="color:blue;"&gt;where &lt;/span&gt;S : T;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In fact, the two interfaces shown here sort of add an additional layer of complexity as was the case in the application I was staring at. The above should fail to compile: since IMyIO&amp;lt;T&amp;gt; declares T as a covariant (output-only) type parameter, it should not be possible to inject an object of type T, or any of its subtypes, into it. So Inject should not work. And indeed it didn’t compile:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Invalid variance: The type parameter &amp;#39;T&amp;#39; must be contravariantly valid on &amp;#39;IMyIO&amp;lt;T&amp;gt;.Inject&amp;lt;S&amp;gt;(S)&amp;#39;. &amp;#39;T&amp;#39; is covariant.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What this says is that Inject requires T to be contravariant (available for input positions) but it’s declared to be covariant. Good job dear compiler (and its developers), just what I expected to see here! Still, that was what I was &lt;em&gt;observing &lt;/em&gt;in the concrete fruity flavored sample shown to me. To make matters worse, we were dealing with concrete types implementing the interfaces, so things were far less obvious than they are in the sample shown above. Going back to the questions I asked to the reader earlier, it’s clear the Inject method in the Fruit-sample is coming from an extension method definition, as the left-hand side is an interface that doesn’t have the method by itself:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EvilLooking
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; Inject&amp;lt;T, S&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; source, S s) &lt;span style="color:blue;"&gt;where &lt;/span&gt;S : T
    {
        &lt;span style="color:green;"&gt;// Implementation doesn&amp;#39;t matter yet...
        &lt;/span&gt;&lt;span style="color:blue;"&gt;return null&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Well, clearly this is fine. Inject is just a method sitting on the outside of the type it extends (in this case IObservable&amp;lt;T&amp;gt;), hence it cannot reach into its internals in any way. The syntactical characteristic of extension method invocation as if it were an instance method simply threw me off:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;fruits.Inject(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Banana&lt;/span&gt;());&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Even though it &lt;strong&gt;looks like&lt;/strong&gt; the &lt;em&gt;covariant &lt;/em&gt;Fruit container &lt;em&gt;accepts &lt;/em&gt;an object of &lt;em&gt;subtype &lt;/em&gt;Banana, were not doing so. The three words “covariant”, “accepts” and “subtype” are a &lt;strong&gt;contradictio in terminis&lt;/strong&gt;. Valid triplets are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;contravariant, accept, subtype – e.g. an IComparer&amp;lt;Fruit&amp;gt; can &lt;strong&gt;accept&lt;/strong&gt; Apple objects since IComparer&amp;lt;T&amp;gt; is contravariant in T&lt;/li&gt;

  &lt;li&gt;covariant, return, subtype – e.g. an IEnumerable&amp;lt;Fruit&amp;gt; can &lt;strong&gt;return&lt;/strong&gt; Apple objects since IEnumerable&amp;lt;T&amp;gt; is covariant in T&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All that’s happening is here is that a “peer method” (with no more “privileges” than the caller in terms of reaching out to the fruits object’s state and internals) is being called:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EvilLooking&lt;/span&gt;.Inject(fruits, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Banana&lt;/span&gt;());&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here it’s clear that fruits is not accepting a Banana directly. And obviously the “Implementation doesn’t matter yet…” comment in the Inject method implementation shown above is wishful thinking. It won’t be able to &lt;em&gt;contaminate&lt;/em&gt; the IObservable&amp;lt;T&amp;gt; source object with an S object (where S is a subtype of T) no matter how hard it tries (short of reflection-based techniques that will fail &lt;em&gt;at runtime&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Case solved. Remaining work for the night was to come up with a good illustration (recall the real problem was not with Fruit, Banana or Apple objects, nor with IObservable&amp;lt;T&amp;gt; directly, but with less intuitive types) of how:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The extension method doesn’t break safety at all, though it looks as if it does (to the trained covariant eye);&lt;/li&gt;

  &lt;li&gt;Co- and contravariance are a great feature;&lt;/li&gt;

  &lt;li&gt;And maybe throwing in some of the dangers of dynamic typing when used inappropriately (a tangent to the original topic).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Extension methods ain&amp;#39;t Trojan horses&lt;/h1&gt;

&lt;p&gt;Here’s what I came up with on the bus heading home: the story of how the &lt;a href="http://en.wikipedia.org/wiki/Trojan_War"&gt;Trojan War&lt;/a&gt; could have been gone differently if the city of &lt;a href="http://en.wikipedia.org/wiki/Troy"&gt;Troy&lt;/a&gt; protected itself against the &lt;a href="http://en.wikipedia.org/wiki/Trojan_horse"&gt;Trojan horse&lt;/a&gt; adequately... Lots of references to this story appear in the code below, so keep a copy of the linked pages on the side (using &lt;a href="http://windows.microsoft.com/en-us/windows7/products/features/snap"&gt;Windows 7 Snap&lt;/a&gt; if you have installed the &lt;a href="http://windows.microsoft.com/en-US/windows7/products/home?os=win7"&gt;brand new wonderful OS&lt;/a&gt; already). I hope you have as much fun reading it (and working your way through it as bedside lecture) as I wrote it. I know, it’s geeky humor at best. And analogies are just that: analogies. I don’t guarantee it to be perfect.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;/* Extension methods ain&amp;#39;t Trojan horses
 * 
 * Illustration of safety guarantees provided by generic covariance in C# 4.0
 * and how extension methods can merely provide a fata morgana making you
 * believe they can defeat it.
 * 
 * bartde - 10/22/2009
 */
&lt;/span&gt;&lt;span style="color:blue;"&gt;using &lt;/span&gt;System;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;System.Collections.Generic;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;System.Dynamic;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;System.Threading;
&lt;span style="color:blue;"&gt;using &lt;/span&gt;Microsoft.CSharp.RuntimeBinder;

&lt;span style="color:green;"&gt;// How the Trojan war could have been...
&lt;/span&gt;&lt;span style="color:blue;"&gt;namespace &lt;/span&gt;NewTrojanWar
{
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Running the attack vector!
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Program
    &lt;/span&gt;{
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Proves the attack DOESN&amp;#39;T work.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main()
        {
            &lt;span style="color:blue;"&gt;try
            &lt;/span&gt;{
                &lt;span style="color:#2b91af;"&gt;GreekArmy&lt;/span&gt;.TheOneAndOnly.Attack();
            }
            &lt;span style="color:blue;"&gt;catch &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;EntryPointNotFoundException &lt;/span&gt;ex)
            {
                &lt;span style="color:green;"&gt;// Ouch. &amp;quot;The gates are closed it says.&amp;quot; Maybe they are covariant after all?
                // They got smarter than we thought! Did they hire Anderius?
                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(ex);

                &lt;span style="color:green;"&gt;// What happened to Epeius is left to your own imagination...
            &lt;/span&gt;}
        }
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;City protected by covariance.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;typeparam name=&amp;quot;NotAllowedToComeIn&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Persona or objects of this type are not allowed to come in.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ISecureCity&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;out &lt;/span&gt;NotAllowedToComeIn&amp;gt;
    {
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;What can&amp;#39;t come in, can go out.
        &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;You&amp;#39;re fine to leave, but beware of the point of no return!&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
        &lt;/span&gt;NotAllowedToComeIn Escape();

        &lt;span style="color:green;"&gt;/* Thanks to Laocoon and Cassandra, the following is not possible anymore due the covariantly
         * protected city. The Trojans are a little unhappy as the annual horse meeting can&amp;#39;t come in
         * anymore though. It was quite an invasion every year; too bad we lost it since Laocoon and
         * Cassandra put their Troy Sharp 4.0 plan into action. The fact they convinced us that the
         * city has support for covariant protection in place since the Troy City Council 2.0 came out
         * almost five years ago, we - the Trojans - are convinced that cancelling the annual horse
         * meeting for additional protection is a good thing. Out with those foreign horses!
         */
        //void Invade(NotAllowedToComeIn evil);
    &lt;/span&gt;}

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Base class for every horse.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Horse
    &lt;/span&gt;{
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Troy doesn&amp;#39;t want horses to come in.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;sealed &lt;/span&gt;&lt;span style="color:green;"&gt;/* we&amp;#39;re an incredibly safe city, no-one should override us! */ &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Troy &lt;/span&gt;:
        &lt;span style="color:#2b91af;"&gt;DynamicObject &lt;/span&gt;&lt;span style="color:green;"&gt;/* Another protection put in place by Laocoon and Cassandra, see further... */&lt;/span&gt;,
        &lt;span style="color:#2b91af;"&gt;ISecureCity&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Horse &lt;/span&gt;&lt;span style="color:green;"&gt;/* Laocoon and Cassandra were right */&lt;/span&gt;&amp;gt;
    {
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;We constructed it ourselves and are proud of it.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;private &lt;/span&gt;Troy()
        {
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;There&amp;#39;s only one real Troy!
        &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 &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Troy &lt;/span&gt;s_city;

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;For publication in the Easy Jet brochure.
        &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;Attractive city in the sun; and safe against incoming horses!&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ISecureCity&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Horse&lt;/span&gt;&amp;gt; City
        {
            &lt;span style="color:blue;"&gt;get
            &lt;/span&gt;{
                &lt;span style="color:blue;"&gt;if &lt;/span&gt;(s_city == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
                    s_city = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Troy&lt;/span&gt;();
                &lt;span style="color:blue;"&gt;return &lt;/span&gt;s_city;
            }
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Troy breeds horses and people can ask for them from the outside.
        &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;You want a horse? Have one!&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Horse &lt;/span&gt;Escape()
        {
            &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Horse&lt;/span&gt;();
        }

        &lt;span style="color:green;"&gt;/* Sigh. This used to be fun. To be a good covariant citizen, we have to drop it for
         * better or for worse. Now we implement the new ISecureCity interface!
        /// &amp;lt;summary&amp;gt;
        /// Horse parade.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;parade&amp;quot;&amp;gt;External horses.&amp;lt;/param&amp;gt;
        [Obsolete]
        public void Invade(Horse parade) // implemented the invariant old ICity interface
        {
            // Hang out in the streets and watch the horse parade coming in through the gates.
        }
         */

        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;We&amp;#39;ll pretend to accept dynamic calls.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;binder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Greek language invocation.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
        /// &amp;lt;param name=&amp;quot;args&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;What are they saying?&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
        /// &amp;lt;param name=&amp;quot;result&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;We won&amp;#39;t every talk to them though...&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;Hard cheese.&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 bool &lt;/span&gt;TryInvokeMember(&lt;span style="color:#2b91af;"&gt;InvokeMemberBinder &lt;/span&gt;binder, &lt;span style="color:blue;"&gt;object&lt;/span&gt;[] args, &lt;span style="color:blue;"&gt;out object &lt;/span&gt;result)
        {
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EntryPointNotFoundException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;The gates are closed!&amp;quot;&lt;/span&gt;);
        }
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Greeks trying to attack will need to sit in the horse for quite a while till
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;the Trojans wheel the horse in.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ICanSitStill
    &lt;/span&gt;{
        &lt;span style="color:blue;"&gt;void &lt;/span&gt;SitStill();
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Greeks trying to attack by creating a special horse.
    &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;Objects to put inside the horse.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/typeparam&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FilledHorse&lt;/span&gt;&amp;lt;T&amp;gt; : &lt;span style="color:#2b91af;"&gt;Horse &lt;/span&gt;&lt;span style="color:blue;"&gt;where &lt;/span&gt;T : &lt;span style="color:#2b91af;"&gt;ICanSitStill
    &lt;/span&gt;{
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;The Trojans will be curious to see what&amp;#39;s inside the horse and will subscribe
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;to the present to receive whatever is in there. Greeks will invade through the
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;well-known OnNext method that fires the attack inside the city walls.
        &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 &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt; Present { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Non-HR-compliant base class for the type below, but according to the story all soldiers were men.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Male
    &lt;/span&gt;{
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Soldiers need to be tough men.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;sealed &lt;/span&gt;&lt;span style="color:green;"&gt;/* inheritance is not allowed in the army */ &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;GreekSoldier &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Male&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;ICanSitStill
    &lt;/span&gt;{
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Event to launch the attack.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;internal &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ManualResetEvent &lt;/span&gt;GoGoGo { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Wait for the attack to start.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;SitStill()
        {
            GoGoGo.WaitOne();
            &lt;span style="color:green;"&gt;// Really they looked for the city&amp;#39;s gates and let in their friends. But let&amp;#39;s assume they were
            // particularly eager to attack straight away. No matter what they do, thanks to the new city&lt;br /&gt;            // security plan, they won’t even get here: Troy won’t burn!&lt;/span&gt;&lt;span style="color:green;"&gt;
            &lt;/span&gt;&lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DestroyTroyException&lt;/span&gt;();
        }
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Destroy Troy!
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DestroyTroyException &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Exception
    &lt;/span&gt;{
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;A present for the Trojans.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;sealed &lt;/span&gt;&lt;span style="color:green;"&gt;/* don&amp;#39;t mess with us! */ &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InterestingHorse
        &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;FilledHorse&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier &lt;/span&gt;&lt;span style="color:green;"&gt;/* Let&amp;#39;s hope they don&amp;#39;t look at the type label at the &amp;quot;base&amp;quot; of the horse. */&lt;/span&gt;&amp;gt;
    {
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Invaders.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier&lt;/span&gt;&amp;gt; _soldiers;

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Fill the horse with invaders. Make internal not to arouse suspicion.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;soldiers&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Invaders.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;internal void &lt;/span&gt;FillWith(&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier&lt;/span&gt;&amp;gt; soldiers)
        {
            _soldiers = soldiers;
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;You got a present! Get it and listen to it :-).
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;remarks&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Typed as a mysterious observable of objects. Little do they know the objects are soldiers.&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 &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt; Present
        {
            &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;WaitingInvaders&lt;/span&gt;(_soldiers); }
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Other than a regular horse, it can be wheeled in.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;Wheel()
        {
            &lt;span style="color:green;"&gt;// This should really override the Horse&amp;#39;s feet.
        &lt;/span&gt;}

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;But the horse is full of invaders waiting till the attack has to happen at night.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;WaitingInvaders &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier&lt;/span&gt;&amp;gt;
        {
            &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
            /// &lt;/span&gt;&lt;span style="color:green;"&gt;Invaders.
            &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
            &lt;/span&gt;&lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier&lt;/span&gt;&amp;gt; _soldiers;

            &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
            /// &lt;/span&gt;&lt;span style="color:green;"&gt;Creating new waiting invaders.
            &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
            /// &amp;lt;param name=&amp;quot;soldiers&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Invaders sitting still.&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;WaitingInvaders(&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier&lt;/span&gt;&amp;gt; soldiers)
            {
                _soldiers = soldiers;
                &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;invader &lt;span style="color:blue;"&gt;in &lt;/span&gt;_soldiers)
                    invader.SitStill();
            }

            &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
            /// &lt;/span&gt;&lt;span style="color:green;"&gt;Curious Trojans will definitely call this.
            &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
            /// &amp;lt;param name=&amp;quot;observer&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The curious Trojans will observe.&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;It doesn&amp;#39;t give you back something to unsubscribe. In a disappointment, the Trojans go to bed.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
            &lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IDisposable &lt;/span&gt;Subscribe(&lt;span style="color:#2b91af;"&gt;IObserver&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier&lt;/span&gt;&amp;gt; observer)
            {
                &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Thread&lt;/span&gt;(() =&amp;gt;
                    {
                        &lt;span style="color:green;"&gt;// Wait till the night falls. We anticipate there will be at most 12 hours of celebration
                        // from the time they wheel in the horse. Then all Trojans will be drunk and asleep.
                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Thread&lt;/span&gt;.Sleep(&lt;span style="color:brown;"&gt;12 &lt;/span&gt;* &lt;span style="color:brown;"&gt;60 &lt;/span&gt;* &lt;span style="color:brown;"&gt;60 &lt;/span&gt;* &lt;span style="color:brown;"&gt;1000&lt;/span&gt;);

                        &lt;span style="color:green;"&gt;// If coast is clear...
                        &lt;/span&gt;&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;invader &lt;span style="color:blue;"&gt;in &lt;/span&gt;_soldiers)
                        {
                            observer.OnNext(invader);
                            &lt;span style="color:green;"&gt;// Wake-up call! Don&amp;#39;t ask me what alarm mechanism they used back then... For one thing,
                            // it wasn&amp;#39;t the Windows 7 kernel&amp;#39;s thread scheduler.
                            &lt;/span&gt;invader.GoGoGo.Set();
                        }
                    }).Start();

                &lt;span style="color:blue;"&gt;return null&lt;/span&gt;; &lt;span style="color:green;"&gt;// if you try to dispose the attackers, you&amp;#39;ll null-ref yourself :P
            &lt;/span&gt;}
        }
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;There&amp;#39;s this evil invader that believes in static typing, hence he declared himself as a classy
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;static man. He can&amp;#39;t have anything but static things. In a evil mood, he decided to help out the
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;Greek army by building the horse and providing an invasion plan for them to enter Troy.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Epeius
    &lt;/span&gt;{
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Build the horse.
        &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;The invading horse.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InterestingHorse &lt;/span&gt;BuildHorse()
        {
            &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InterestingHorse&lt;/span&gt;();
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;How evil. Putting a Gift method before the city door. How could you resist
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;calling it? But Epeius is faking it, as we shall see. The city is protected
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &lt;/span&gt;&lt;span style="color:green;"&gt;quite well thanks to the Troy Sharp 4.0 feature.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name=&amp;quot;city&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;The city to invade.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
        /// &amp;lt;param name=&amp;quot;present&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Hmm, horse beef (assuming the Trojans are not vegetarian)!&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static void &lt;/span&gt;Gift(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ISecureCity&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Horse&lt;/span&gt;&amp;gt; city, &lt;span style="color:#2b91af;"&gt;InterestingHorse &lt;/span&gt;present)
        {
            &lt;span style="color:green;"&gt;// Sometimes Epeius silently surrenders to dynamic typing because he&amp;#39;s lazy.
            // No-one will suspect him to describe Troy as a dynamic vibrant city. After
            // all, they eagerly want to get into it and Epeius was pretty excited about
            // his job for the Greek army helping them to invade the city. No reason for
            // suspicion at all. We believe Epeius&amp;#39; use of dynamic is fine...
            &lt;/span&gt;&lt;span style="color:blue;"&gt;dynamic &lt;/span&gt;vibrantTroy = city;

            &lt;span style="color:green;"&gt;// But Epeius didn&amp;#39;t find (statically) a method or property on city that accepts
            // the present. He makes the Greek army believe this method works by putting
            // dynamic fairy dust in their eyes though. In fact, Epeius fails here and will
            // let down the Greek army: there is no way to invade Troy. So, the invasion
            // plan (the compiled IL) contains some hidden decision logic on finding out how
            // to carry out the invasion (the DLR machinery behind the scenes). When the
            // soldiers are in the horse, they&amp;#39;ll eventually fail right here and their horse&lt;br /&gt;            // will explode (see DynamicObject::TryInvokeMember method implementation!).
            &lt;/span&gt;vibrantTroy.Invade(present);

            &lt;span style="color:green;"&gt;// Unfortunately, Epeius made himself so static he even doesn&amp;#39;t have a this
            // reference to call .Escape() on himself. The rest of the story of what happened
            // with Epeius after the Greek army discovered he cheated on them is not for the
            // sensitive reader.
        &lt;/span&gt;}
    }

    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;The Greek army is cruel.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;GreekArmy
    &lt;/span&gt;{
        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Army.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;GreekSoldier&lt;/span&gt;&amp;gt; _soldiers;

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Only one!
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;private &lt;/span&gt;GreekArmy()
        {
            _soldiers = &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;GreekSoldier&lt;/span&gt;&amp;gt; { &lt;span style="color:green;"&gt;/* recruit good fighters */ &lt;/span&gt;};
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Only one!
        &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 &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;GreekArmy &lt;/span&gt;s_army;

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Only one!
        &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;Only one!&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/returns&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;GreekArmy &lt;/span&gt;TheOneAndOnly
        {
            &lt;span style="color:blue;"&gt;get
            &lt;/span&gt;{
                &lt;span style="color:blue;"&gt;if &lt;/span&gt;(s_army == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
                    s_army = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;GreekArmy&lt;/span&gt;();
                &lt;span style="color:blue;"&gt;return &lt;/span&gt;s_army;
            }
        }

        &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
        /// &lt;/span&gt;&lt;span style="color:green;"&gt;Written by Odysseus who believes Epeius&amp;#39; poisonous Gift call on the City of Troy will work.
        &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
        &lt;/span&gt;&lt;span style="color:blue;"&gt;public void &lt;/span&gt;Attack()
        {
            &lt;span style="color:blue;"&gt;var &lt;/span&gt;horse = &lt;span style="color:#2b91af;"&gt;Epeius&lt;/span&gt;.BuildHorse();
            horse.FillWith(_soldiers);
            &lt;span style="color:#2b91af;"&gt;Troy&lt;/span&gt;.City.Gift(horse); &lt;span style="color:green;"&gt;// Sweet, Odysseus sees a Gift command he can shout to the City of Troy...&lt;/span&gt;
        }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;So far for this lecture on Latin epic poems, lectured in C# 4.0.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14848" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>LINQ to Ducks – Bringing Back The Duck-Typed foreach Statement To LINQ</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2009/08/17/linq-to-ducks-bringing-back-the-duck-typed-foreach-statement-to-linq.aspx</link><pubDate>Tue, 18 Aug 2009 03:20:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14709</guid><dc:creator>bart</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14709</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2009/08/17/linq-to-ducks-bringing-back-the-duck-typed-foreach-statement-to-linq.aspx#comments</comments><description>&lt;p&gt;I promise, it will be a (relatively) short post this time. You all know the foreach statement in C#, don’t you? Think twice before you answer and tell me exactly how the following works:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;foreach&lt;/font&gt; (&lt;font color="#0000ff"&gt;int &lt;/font&gt;x &lt;font color="#0000ff"&gt;in &lt;/font&gt;src) &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;{ &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Do something with x.&lt;/font&gt; &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Got an answer? Let me disappoint you: if you have &lt;em&gt;the&lt;/em&gt; answer, you’re &lt;em&gt;wrong&lt;/em&gt;. There’s no single answer to the question above as you need to know more about the type of src to make a final decision on how the above works…&lt;/p&gt;
&lt;p&gt;You may say that clearly that object needs to implement &lt;strong&gt;IEnumerable&lt;/strong&gt; or &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt;, and maybe you’ll even mention that in the former case the compiler inserts a cast for you when it gets “x” back from the call to the IEnumerator’s Current property getter. In other words, the code gets translated like this:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;e = src.GetEnumerator(); &lt;br /&gt;&lt;font color="#0000ff"&gt;while &lt;/font&gt;(e.MoveNext()) &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;var &lt;/font&gt;x = (&lt;font color="#0000ff"&gt;int&lt;/font&gt;)e.Current; &lt;font color="#008000"&gt;// without the cast if src was an IEnumerable&amp;lt;T&amp;gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Do something with x. &lt;br /&gt;&lt;/font&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;A worthy attempt at the translation but not quite right. First of all, the variable x is declared in an outer scope (causing some grief when talking about closures, but that’s a whole different topic…). Secondly, the enumerator may implement IDisposable, in which case the foreach-statement will ensure proper disposal a la “using”:&lt;/p&gt;
&lt;blockquote&gt;&lt;font face="Courier New"&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;int &lt;/font&gt;x; &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;using &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;e = src.GetEnumerator()) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(e.MoveNext()) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x = (&lt;font color="#0000ff"&gt;int&lt;/font&gt;)e.Current; &lt;font color="#008000"&gt;// without the cast if src was an IEnumerable&amp;lt;T&amp;gt;&lt;/font&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#008000"&gt;// Do something with x.&lt;/font&gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;
&lt;p&gt;That’s a bit more sane, but we’re missing out on another kind of source foreach can work with: any object, as long as it exposes the enumeration pattern of GetEnumerator in tandem with MoveNext and Current. Here’s a sample object that just works fine with the foreach-statement:&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;Source
&lt;/span&gt;{
    &lt;span style="COLOR:blue;"&gt;public &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;SourceEnumerator &lt;/span&gt;GetEnumerator()
    {
        &lt;span style="COLOR:blue;"&gt;return new &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;SourceEnumerator&lt;/span&gt;();
    }
}

&lt;span style="COLOR:blue;"&gt;class &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;SourceEnumerator
&lt;/span&gt;{
    &lt;span style="COLOR:blue;"&gt;private &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;Random &lt;/span&gt;rand = &lt;span style="COLOR:blue;"&gt;new &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;Random&lt;/span&gt;();

    &lt;span style="COLOR:blue;"&gt;public bool &lt;/span&gt;MoveNext()
    {
        &lt;span style="COLOR:blue;"&gt;return &lt;/span&gt;rand.Next(100) != 0;
    }

    &lt;span style="COLOR:blue;"&gt;public int &lt;/span&gt;Current
    {
        &lt;span style="COLOR:blue;"&gt;get
        &lt;/span&gt;{
            &lt;span style="COLOR:blue;"&gt;return &lt;/span&gt;rand.Next(100);
        }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;With its usage shown below:&lt;/p&gt;
&lt;blockquote&gt;&lt;/blockquote&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;span style="COLOR:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="COLOR:blue;"&gt;int &lt;/span&gt;x &lt;span style="COLOR:blue;"&gt;in new &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;Source&lt;/span&gt;())
    &lt;span style="COLOR:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(x);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Okay, that’s flexible, isn’t it? In fact, the foreach-statement can be said to be &lt;strong&gt;duck typed&lt;/strong&gt;: it’s not the &lt;em&gt;nominal&lt;/em&gt; type that matters (i.e. Source is explicitly declared to be an IEnumerable, and SourceEnumerator an IEnumerator) but just the &lt;em&gt;structure &lt;/em&gt;of the object that determines “compatibility” with the foreach-statement.&lt;/p&gt;
&lt;p&gt;But who says foreach over a collection immediately starts thinking about LINQ, no? Say the consumer of Source looked like this:&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:blue;"&gt;int&lt;/span&gt;&amp;gt; res = &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:blue;"&gt;int&lt;/span&gt;&amp;gt;();
&lt;span style="COLOR:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="COLOR:blue;"&gt;int &lt;/span&gt;x &lt;span style="COLOR:blue;"&gt;in new &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;Source&lt;/span&gt;())
    &lt;span style="COLOR:blue;"&gt;if &lt;/span&gt;(x % 2 == 0)
        res.Add(x);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;A great candidate for LINQ it seems, especially as we start adding more and more logic to the “query”. Nothing surprising about this conclusion, but trying to realize it fails miserably:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/LINQtoDucksBringingBackTheDuckTypedforea_C038/image.png"&gt;&lt;img style="BORDER-BOTTOM:0px;BORDER-LEFT:0px;DISPLAY:inline;BORDER-TOP:0px;BORDER-RIGHT:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/LINQtoDucksBringingBackTheDuckTypedforea_C038/image_thumb.png" width="683" height="345" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Why? Because LINQ is statically typed &lt;font color="#ff0000"&gt;(&lt;strong&gt;update:&lt;/strong&gt; to be taken with a grain of salt, see comments below this post; agreed, it&amp;#39;d be more precise to write LINQ &lt;em&gt;to Objects&lt;/em&gt; as the subject of this sentence)&lt;/font&gt;, so it expects what I’ve referred to as a &lt;em&gt;nominal&lt;/em&gt; enumerator implementation: something that has explicitly stated to be an IEnumerable and not something that “accidentally” happens to look like that. Question of the day: how to morph an existing &lt;em&gt;structural&lt;/em&gt; enumerator onto a nominal one so it can be used with LINQ? Sure, we could write specialized code for the Source object above that essentially creates an iterator on top of Source:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;span style="COLOR:blue;"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="COLOR:blue;"&gt;var &lt;/span&gt;res = &lt;span style="COLOR:blue;"&gt;from &lt;/span&gt;x &lt;span style="COLOR:blue;"&gt;in &lt;/span&gt;IterateOver(&lt;span style="COLOR:blue;"&gt;new &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;Source&lt;/span&gt;())
              &lt;span style="COLOR:blue;"&gt;where &lt;/span&gt;x % 2 == 0
              &lt;span style="COLOR:blue;"&gt;select &lt;/span&gt;x;

    &lt;span style="COLOR:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="COLOR:blue;"&gt;var &lt;/span&gt;x &lt;span style="COLOR:blue;"&gt;in &lt;/span&gt;res)
        &lt;span style="COLOR:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(x);
}

&lt;span style="COLOR:blue;"&gt;static &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="COLOR:blue;"&gt;int&lt;/span&gt;&amp;gt; IterateOver(&lt;span style="COLOR:#2b91af;"&gt;Source &lt;/span&gt;s)
{
    &lt;span style="COLOR:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="COLOR:blue;"&gt;int &lt;/span&gt;i &lt;span style="COLOR:blue;"&gt;in &lt;/span&gt;s)
        &lt;span style="COLOR:blue;"&gt;yield return &lt;/span&gt;i;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;But maybe you’re in a scenario with plenty of those structural enumerator constructs around (e.g. some Office automation libraries expose GetEnumerator on types like Range, while the Range object itself doesn’t implement IEnumerable hence it’s not usable with LINQ), so you want to generalize the above. Essentially, given any object you’d like to provide a duck-typed iterator over it, a suitable task for another extension method and &lt;strong&gt;C# 4.0 dynamic&lt;/strong&gt;:&lt;/p&gt;
&lt;blockquote&gt;&lt;/blockquote&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;span style="COLOR:blue;"&gt;static class &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;DuckEnumerable
&lt;/span&gt;{
    &lt;span style="COLOR:blue;"&gt;public static &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; AsDuckEnumerable&amp;lt;T&amp;gt;(&lt;span style="COLOR:blue;"&gt;this object &lt;/span&gt;source)
    {
        &lt;span style="COLOR:blue;"&gt;dynamic &lt;/span&gt;src = source;

        &lt;span style="COLOR:blue;"&gt;var &lt;/span&gt;e = src.GetEnumerator();
        &lt;span style="COLOR:blue;"&gt;try
        &lt;/span&gt;{
            &lt;span style="COLOR:blue;"&gt;while &lt;/span&gt;(e.MoveNext())
                &lt;span style="COLOR:blue;"&gt;yield return &lt;/span&gt;e.Current;
        }
        &lt;span style="COLOR:blue;"&gt;finally
        &lt;/span&gt;{
            &lt;span style="COLOR:blue;"&gt;var &lt;/span&gt;d = e &lt;span style="COLOR:blue;"&gt;as &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;IDisposable&lt;/span&gt;;
            &lt;span style="COLOR:blue;"&gt;if &lt;/span&gt;(d != &lt;span style="COLOR:blue;"&gt;null&lt;/span&gt;)
            {
                d.Dispose();
            }
        }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;u&gt;Question to the reader:&lt;/u&gt; why can’t we simply write a foreach-loop over the “source casted as dynamic” object? Tip: how would &lt;em&gt;you &lt;/em&gt;implement the translation of foreach when encountering a dynamic object as its source?&lt;/p&gt;
&lt;p&gt;Yes, you’re cluttering the &lt;em&gt;apparent&lt;/em&gt; member list on System.Object, so use with caution or just use plain old method calls to do the “translation”. What matters more is the inside of the operator, using the dynamic type quite a bit to realize the enumeration pattern. Notice how easy on the eye dynamically typed code looks in C# 4.0. With much more casts, it’d look like this:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;span style="COLOR:blue;"&gt;static class &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;DuckEnumerable
&lt;/span&gt;{
    &lt;span style="COLOR:blue;"&gt;public static &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; AsDuckEnumerable&amp;lt;T&amp;gt;(&lt;span style="COLOR:blue;"&gt;this object &lt;/span&gt;source)
    {
        &lt;span style="COLOR:blue;"&gt;dynamic &lt;/span&gt;src = (&lt;span style="COLOR:blue;"&gt;dynamic&lt;/span&gt;)source;

        &lt;span style="COLOR:blue;"&gt;dynamic &lt;/span&gt;e = src.GetEnumerator();
        &lt;span style="COLOR:blue;"&gt;try
        &lt;/span&gt;{
            &lt;span style="COLOR:blue;"&gt;while &lt;/span&gt;((&lt;span style="COLOR:blue;"&gt;bool&lt;/span&gt;)e.MoveNext())
                &lt;span style="COLOR:blue;"&gt;yield return &lt;/span&gt;(T)e.Current;
        }
        &lt;span style="COLOR:blue;"&gt;finally
        &lt;/span&gt;{
            &lt;span style="COLOR:blue;"&gt;var &lt;/span&gt;d = e &lt;span style="COLOR:blue;"&gt;as &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;IDisposable&lt;/span&gt;;
            &lt;span style="COLOR:blue;"&gt;if &lt;/span&gt;(d != &lt;span style="COLOR:blue;"&gt;null&lt;/span&gt;)
            {
                d.Dispose();
            }
        }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;And now we can write:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;span style="COLOR:blue;"&gt;var &lt;/span&gt;res = &lt;span style="COLOR:blue;"&gt;from &lt;/span&gt;x &lt;span style="COLOR:blue;"&gt;in new &lt;/span&gt;&lt;span style="COLOR:#2b91af;"&gt;Source&lt;/span&gt;().AsDuckEnumerable&amp;lt;&lt;span style="COLOR:blue;"&gt;int&lt;/span&gt;&amp;gt;()
          &lt;span style="COLOR:blue;"&gt;where &lt;/span&gt;x % 2 == 0
          &lt;span style="COLOR:blue;"&gt;select &lt;/span&gt;x;

&lt;span style="COLOR:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="COLOR:blue;"&gt;var &lt;/span&gt;x &lt;span style="COLOR:blue;"&gt;in &lt;/span&gt;res)
    &lt;span style="COLOR:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(x);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Dynamic glue – why not? In fact, even objects from other languages (like Ruby or Python) that follow the pattern will now work with LINQ, and for existing compatible objects the operator call is harmless (but wasteful). Oh, and notice you can also have an IEnumerable of “dynamic” objects if you’re dealing with objects originating from dynamic languages...&lt;/p&gt;
&lt;p&gt;Can you implement the AsDuckEnumerable operator in C# 3.0? Absolutely, if you limit yourself to reflection-based discovery methods (left as an exercise for the reader).&lt;/p&gt;
&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14709" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>(Mis)using C# 4.0 Dynamic – Type-Free Lambda Calculus, Church Numerals, and more</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2009/08/17/mis-using-c-4-0-dynamic-type-free-lambda-calculus-church-numerals-and-more.aspx</link><pubDate>Mon, 17 Aug 2009 08:35:36 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14702</guid><dc:creator>bart</dc:creator><slash:comments>14</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14702</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2009/08/17/mis-using-c-4-0-dynamic-type-free-lambda-calculus-church-numerals-and-more.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;Sunday morning, time for another episode of the Crazy Sundays series. Again one in the category with risk for &lt;a href="http://www.bing.com/images/search?q=exploding+head&amp;amp;form=QBIR&amp;amp;qs=n#"&gt;exploding brains&lt;/a&gt;, but that’s what we like, don’t we? This time around, we’re going to have a look at the type free lambda calculus in C#. But wait a minute, isn’t C# a typed language? True. Does that mean everything you do in it should be statically typed? Not necessarily: typing is there as a tool you can leave or take. In this post we’ll take a look at the new C# 4.0 dynamic feature (which provides a &lt;em&gt;static&lt;/em&gt; type to do &lt;em&gt;dynamic&lt;/em&gt; dispatch) from a somewhat bizarre angle…&lt;/p&gt;  &lt;p&gt;Sometimes types do get in the way: maybe something is intrinsically untyped (like XML documents without a schema, web services without a WSDL contract, etc) or meant to be dynamically typed (like objects coming from a dynamic language like Ruby or Python). And then there are notorious APIs that “peter out” in their typing: one moment you’re statically typed, but all of a sudden you end up with System.Object everywhere (like with COM interop to the Office libraries). All such scenarios are what C# 4.0 dynamic is meant for. The classical sample to illustrate the feature is to talk to an IronPython object from C#. First the Python definition:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;class Calc:      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; def Add(self, a, b):       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; return a + b       &lt;br /&gt;def GetCalc():       &lt;br /&gt;&amp;#160;&amp;#160; return Calc()&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The nice thing about this Python-based calculator is that it will work with anything that supports an addition operator. In other words, we could feed it two int objects, two string objects, or even a DateTime and a TimeSpan. To make such calls, we use the dynamic keyword in C#:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;py = &lt;span style="color:#2b91af;"&gt;Python&lt;/span&gt;.CreateEngine();
&lt;span style="color:blue;"&gt;dynamic &lt;/span&gt;script = py.ImportModule(&lt;span style="color:#a31515;"&gt;&amp;quot;Calc&amp;quot;&lt;/span&gt;);

&lt;span style="color:blue;"&gt;dynamic &lt;/span&gt;calc = script.GetCalc();
&lt;span style="color:blue;"&gt;int &lt;/span&gt;three = calc.Add(1, 2);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ignore the few lines of plumbing to load the Python file; what matters here is the fact the calc variable is typed to be “dynamic”, meaning all operations invoked on it will be resolved at runtime:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb.png" width="376" height="149" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I won’t go into details on how all of this works, maybe another time (outside the scope of Crazy Sundays posts), but that’s the essence of the feature. Instead, we’re going to push this feature to the limits in a “don’t try this at &lt;strike&gt;home&lt;/strike&gt;work” style: enter &lt;strong&gt;type free lambda calculus&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Type free lambda calculus in a nutshell&lt;/h1&gt;

&lt;p&gt;The type free lambda calculus, due to &lt;a href="http://en.wikipedia.org/wiki/Alonzo_Church"&gt;Alonzo Church&lt;/a&gt; around 1930, is a theory about the &lt;strong&gt;computational &lt;/strong&gt;aspects of &lt;strong&gt;functions&lt;/strong&gt;. It views functions as rules and defines two complimentary operations to work with those: &lt;strong&gt;abstraction &lt;/strong&gt;and &lt;strong&gt;application&lt;/strong&gt;. In essence, that’s all there is but nevertheless the theory gives rise to a whole research area of its own. To convince you about that statement, check the page count for the following book on your favorite online bookshop:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;img src="http://ecx.images-amazon.com/images/I/41BRXJ7E7GL._SS500_.jpg" width="240" height="240" alt="" /&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So, allow me to summarize the essentials here, citing/paraphrasing the book above (due to the non-trivial nature of mathematical notation, pasted as images from Word equations). First, we need to define the concept of a &lt;strong&gt;lambda term&lt;/strong&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_3.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_3.png" width="613" height="502" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As a typical exercise, expand the fourth lambda term in the examples above to its fully parenthesized and bloated form.&lt;/p&gt;

&lt;p&gt;All there is to lambda terms is they can denote functions, just like lambda expressions in C# do. For example, the second sample above is a function with argument “x”, returning “x”. In other words, it’s the identity function. However, it has no type: it can operate on anything (in particular, any other lambda term). In C# we could write this as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;T, T&amp;gt; I = x =&amp;gt; x;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;where T stands for a generic parameter. It’s clear this function can operate on values but equally well it can operate on functions: given a function, it will return exactly that function:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;I(5) // produces 5 
      &lt;br /&gt;I(I) // produces I&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In fact, the middle three samples above are &lt;em&gt;closed terms&lt;/em&gt;, meaning all symbols used in their “function body” (the part after the dot) are in “scope” by means of the abstraction(s) over it. We call those &lt;strong&gt;combinators&lt;/strong&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_4.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_4.png" width="298" height="120" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The last sample term in the previous sample is not closed though: it returns “x” which is not being abstracted over. This reflects the concept of a &lt;em&gt;closure&lt;/em&gt;, just as we have in C#:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;R x = …; 
      &lt;br /&gt;Func&amp;lt;T, R&amp;gt; f = z =&amp;gt; x;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s not go there for now, but suffice to say that fancy words like “closure” are deeply rooted in theoretical foundations. Praise yourself lucky to work with a language layered on top of solid theoretical foundations :-).&lt;/p&gt;

&lt;p&gt;Next, we need the concept of &lt;strong&gt;free variables&lt;/strong&gt;. In short, this allows us to identify those variables not introduced by an abstraction in a given term. The definition is fairly straightforward:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_5.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_5.png" width="254" height="118" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For combinators, the free variables set will be empty. In contrast, for our last sample (the one resulting in a closure) the set would be a singleton containing “x”. Nothing too fancy, right?&lt;/p&gt;

&lt;p&gt;Finally, we can define how &lt;strong&gt;application&lt;/strong&gt; is carried out, based on the concept of &lt;strong&gt;substitution&lt;/strong&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_6.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_6.png" width="654" height="243" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To avoid name clashes (something that can be formally avoided by using a variable convention, using the definition of FV above), we notice careful renames are possible. We all know this from C#, and this is merely a theoretical foundation for &lt;em&gt;scoping&lt;/em&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;T, T&amp;gt; I1 = x =&amp;gt; x;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;T, T&amp;gt; I2 = y =&amp;gt; y;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;are in fact the “same”. Using such a big word in the context of a whole runtime (CLR) and language (C#) is a dangerous business. I’m not saying that I1 and I2 will refer to the same delegate: there’s no identification between delegates that says “x =&amp;gt; x” and “y =&amp;gt; y” are the same. Rather, what I’m pointing out here is that the &lt;em&gt;behavior&lt;/em&gt; of I1 and I2 will be the same when applied to the same object. In the lambda calculus this is referred to as alpha-conversion.&lt;/p&gt;

&lt;p&gt;Ignoring the important concern of avoiding name clashes for the time being, have a closer look at the application “&lt;strong&gt;beta-conversion&lt;/strong&gt;” rule above. The idea is simple: “application of an abstraction with another term results in substitution”. This is pretty much like a delegate call in C#, but yet different enough: in the world of the lambda calculus, substitutions are nothing but mechanical rewrites on terms. In languages like C#, code is compiled as-is and delegate calls don’t magically rewrite the delegate’s body on the fly. But more importantly, in C# we get also immediately concerned with call semantics like call-by-value: before making a call, its arguments need to be reduced to a “value” that can be passed to the receiving end of the call (through the delegate invocation mechanism).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Untyped or uni-typed?&lt;/h1&gt;

&lt;p&gt;Now the question of the day: &lt;strong&gt;can we type (in the CLR/C# type system sense) all lambda terms&lt;/strong&gt;? It seems we were successful doing so already with the I combinator, concluding it’s a Func&amp;lt;T, T&amp;gt; with the use of generics: passing a value of a certain type T, the result it the same value and hence of the same type. In fact, what about inferring such signatures? C# doesn’t do so, but F# can (through Hindley-Milner type inference as is done typically in ML-inspired languages):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_7.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_7.png" width="677" height="222" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Okay, “I” is inferred to be a type that goes from ‘a to ‘a, where ‘a is the notation for a generic parameter. What about K, the combinator that given two arguments always returns that first one (“constant” value producer):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_8.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_8.png" width="677" height="222" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We’re still good to go it seems. F# has inferred the type ought to be “‘a to ‘b to ‘a”. Wow, what’s going on here? In C#, this would look like Func&amp;lt;T1, Func&amp;lt;T2, T1&amp;gt;&amp;gt;: a function that given an argument of type T1 returns a function that given an argument of type T2 returns a value of type T1. Get it? What’s happening here is “currying”, where a function of n arguments is turned into “nested” functions that consume one argument at a time. This means we can write, say, “K 5” to create a new function that will eat the remaining “y” argument (of any type) and will always return 5.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; There’s a little complication here in the context of F#, called the “value restriction”. I won’t go there as this is irrelevant for the discussion here. What we’re focusing on is solely whether or not we can type lambda expressions.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Even for the (relatively) complicated beast S, a type can be inferred:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_9.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_9.png" width="677" height="222" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Impressive? Not so hard in fact. Follow me as we infer the type ourselves by hand, from the function’s body. First of all, we see x followed by two terms: “z” and “(y z)”. That means “x” is a function with two arguments, and we assume it returns something. Assign type names for those things: the first argument “z” gets type ‘a and the result of “(y z)” will get type ‘b. For the result we write ‘c. In other words, the type of “x” is already inferred to be ’a –&amp;gt; ‘b –&amp;gt; ‘c. Next, we need to infer the type for “y” based on our prior identification of the type for “(y z)” as ’b. We see that “y” is a function with one argument, “z”. We already typed “z” to be ‘a, so the type of “y” becomes ‘a –&amp;gt; ‘b. And finally, our “S” function also takes in “z” as a third argument, which is typed to be ‘a. All of this brought together with the return type of the call to “x” leads to the signature shown above.&lt;/p&gt;

&lt;p&gt;So, it looks like we can type all lambda terms, right? Unfortunately, &lt;strong&gt;no&lt;/strong&gt;. Here’s the proof:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_10.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_10.png" width="677" height="294" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here I’ve written a function W that given an argument x applies that to itself. Such a simple lambda term, and yet one can’t find a type for it. Follow me on this brain exercise: W takes one argument x, say of type ‘a. Now, x is applied to x. From this it looks like x is a function type with one argument. The argument is x, which we’ve already typed to be ‘a. What about the return type? Let’s say it’s ‘b, so now we have that x needs to be of type ‘a –&amp;gt; ‘b, which isn’t the same as ‘a we had before: &lt;em&gt;unification &lt;/em&gt;fails.&lt;/p&gt;

&lt;p&gt;That’s where differences between the type free lambda calculus and typed variants (like the simply typed lambda calculus and for generics and such something called “System F”) crop up. C# being a typed language doesn’t allow us to get rid of types altogether, so there’s no way we can get “untyped”. But what about “uni-typed” (due to &lt;a href="http://www.cs.cmu.edu/~rwh/"&gt;Robert Harper&lt;/a&gt;): replace all types with one single type. Can we get there? The answer is, with “dynamic” we can!&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;dynamic &lt;/span&gt;W = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(x =&amp;gt; x(x));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The fact we need some ugly delegate constructor call is unfortunate, but notice how we’re assigning the “dynamic –&amp;gt; dynamic” type to a “dynamic” on the left. In other words, we’re treating &lt;em&gt;everything&lt;/em&gt; (non-functional values and function “objects” themselves) as dynamic. The code above compiles just fine, but how does the x(x) in the lambda body work? Well, at runtime the system will figure out what the type of x is and ensure it can be used to be called as a unary function. For example:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;dynamic &lt;/span&gt;W = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(x =&amp;gt; x(x));
W(1);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will clearly fail. It corresponds to “calling the function integer 1” with argument “integer 1”. Clearly, an integer value cannot be used as a function (a good thing!), so a runtime error results:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot invoke a non-delegate type 
      &lt;br /&gt;&amp;#160;&amp;#160; at CallSite.Target(Closure , CallSite , Object , Object ) 

      &lt;br /&gt;&amp;#160;&amp;#160; at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1) 

      &lt;br /&gt;&amp;#160;&amp;#160; at UntypedLambda.Program.&amp;lt;Main&amp;gt;b__46(Object x) 

      &lt;br /&gt;&amp;#160;&amp;#160; at CallSite.Target(Closure , CallSite , Object , Int32 ) 

      &lt;br /&gt;&amp;#160;&amp;#160; at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1) 

      &lt;br /&gt;&amp;#160;&amp;#160; at UntypedLambda.Program.Main()&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;How this works internally is beyond the scope of this post (I’m sure I’ll blog about the DLR machinery and the role of the C# and VB compilers in that mix some time in the relatively near future) but the DLR was right to conclude the call above is nonsense.&lt;/p&gt;

&lt;p&gt;What about the following?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(x =&amp;gt; x);
&lt;span style="color:blue;"&gt;dynamic &lt;/span&gt;W = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(x =&amp;gt; x(x));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(W(I)(42));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, &lt;em&gt;that&lt;/em&gt; works. Passing I to W results in I(I), which reduces (using application, or beta-conversion) into I. That function is then used with argument 42 subsequently, returning 42.&lt;/p&gt;

&lt;p&gt;You can guess it … we’re going to uni-type our whole programs using dynamic in this Crazy Sundays post. Did I ever mention Scheme? If not, I did now :-).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;SKI combinators&lt;/h1&gt;

&lt;p&gt;As we’ve already played with S, K and I in the samples above, let’s see how those look in uni-typed C#:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// Where else to start than with ... SKI combinators.
//
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;S = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;(x =&amp;gt; y =&amp;gt; z =&amp;gt; x(z)(y(z)));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;K = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(x =&amp;gt; y =&amp;gt; x);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(x =&amp;gt; x);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice we’re currying all functions so that we can partially apply functions. For example, we can do the following to create a “constant function” that always returns 42:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;answer = K(42);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(answer(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(answer(&lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(answer(-42));&lt;br /&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(answer(S));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;All of the calls above will print 42, regardless of what’s passed in to answer. Follow the reduction in your head: applying 42 to K returns a function from a parameter called “y” to 42. In other words, “y” is discarded altogether. We’re generating the constant 42, no matter what (both in terms of value and type) we throw to the function as an argument. Not just plain values: in the last line we throw S, another function, to the answer function and yet it persists telling us the answer is 42.&lt;/p&gt;

&lt;p&gt;It can be shown, as an easy exercise, that SKK (and SKS) are the same as I, so the following is a complicated way of writing 5:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;int &lt;/span&gt;five = S(K)(K)(5);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;See how functions are first-class citizens: they can be passed or returned everywhere. Also notice how functions have to be called one argument at a time because of currying (due to &lt;a href="http://en.wikipedia.org/wiki/Moses_Sch%C3%B6nfinkel"&gt;Schonfinkel&lt;/a&gt;, not &lt;a href="http://en.wikipedia.org/wiki/Haskell_Curry"&gt;Curry&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;While we’re at it, we’ll write a helper function to apply a function to different argument values and print the result to the screen. In subsequent paragraphs we’ll use this function (and a variant thereof) to aid us in printing test results:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Unary&amp;lt;T, PArg, PRes&amp;gt;(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, T&amp;gt; f, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, PArg&amp;gt; printArg, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, PRes&amp;gt; printRes, &lt;span style="color:blue;"&gt;params dynamic&lt;/span&gt;[] values)
{
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;value &lt;span style="color:blue;"&gt;in &lt;/span&gt;values)
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;{0}({1}) = {2}&amp;quot;&lt;/span&gt;, name, printArg(value), printRes(f(value)));
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Quite a signature, but essentially we take a friendly function name, a function to be tested, some function to turn the “dynamic” argument into a print-friendly form (and a similar function for the result of the function call), and an array of values to be fed in. For example:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;SKI&amp;quot;&lt;/span&gt;);
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;SKK&amp;quot;&lt;/span&gt;, S(K)(K), I, I, 5, &lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now, &lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;);
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;I&amp;quot;&lt;/span&gt;, I, I, I, 5, &lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now, &lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This results in the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_11.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_11.png" width="677" height="138" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As an exercise, try to do something more meaningful with the S combinator.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Church Booleans&lt;/h1&gt;

&lt;p&gt;Functions and data are very closely related. More closely than you may think. Most programmers think of functions as pieces of code that have a certain behavior and get applied to zero or more arguments, producing some (or none) value. That’s a very code-centric view of the world, while functions in the mathematical sense are obviously not related to “code” at all. Functions are often defined as graphs and are a special kind of relation between two sets. Sets are all about data, aren’t they? Based on such an observation one can establish functions in a computer programs as table lookup = data.&lt;/p&gt;

&lt;p&gt;But there’s more, even values themselves (and not mappings between them) can be &lt;em&gt;encoded &lt;/em&gt;using functions. Let’s start easy, with Booleans. Easy because there are only two values to distinguish. Here’s the proposed mapping:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// Church Booleans.
// Basic idea: true and false are dyadic functions returning respectively
//             the first or second argument, acting as a conditional (?:)
//
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;F = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(a =&amp;gt; b =&amp;gt; b);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;T = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(a =&amp;gt; b =&amp;gt; a);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Okay, the comment reveals it already: the idea is that true and false are encoded as functions with two arguments (again curried) of which one is returned: false returns the second one, true the first one. Sounds familiar, doesn’t it? Right, the conditional operator (sometimes awkwardly referred to as &lt;em&gt;the&lt;/em&gt; ternary operator) in C# does exactly that. Notice that using alpha-conversion, T is exactly the same as K.&lt;/p&gt;

&lt;p&gt;Notice it’s easy to convert between the untyped world and the typed world using two back-and-forth conversion functions:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; toBool = x =&amp;gt; x(&lt;span style="color:blue;"&gt;true&lt;/span&gt;)(&lt;span style="color:blue;"&gt;false&lt;/span&gt;);
&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;bool&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt; fromBool = b =&amp;gt; b ? T : F;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;We wouldn’t need toBool if we weren’t to print the results to the screen somehow :-). For completeness, I’ve added fromBool to the equation. Both are easy to understand, but let’s start with fromBool. Plain easy: give it true, and it returns T; give it false, and you get F back. The inverse function, toBool, is simple function application (beta conversion) of the defined functions to C# Booleans: if the function bound to x is T, the first argument will be returned (true). If it’s F, the second one (false) will. Clear as crystal. Notice toBool can be applied with any object as its argument: going from untyped to typed will &lt;a href="http://homepages.inf.ed.ac.uk/wadler/topics/blame.html"&gt;blame&lt;/a&gt; the argument if something goes wrong (due to &lt;a href="http://homepages.inf.ed.ac.uk/wadler/"&gt;Philip Wadler&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Not very useful yet, if we don’t have a way to define operations between such Booleans. Again functions come to the rescue (we don’t have anything else after all), so let’s have a look at how we define a simple operator: not.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;not = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;(m =&amp;gt; a =&amp;gt; b =&amp;gt; m(b)(a));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice all operators on Church Booleans will be higher-order functions in their very nature, since their arguments are functions already. That’s the nature of the beast we’re dealing with. So, how can we turn a Church Boolean “m” in its opposite? We already know that Church Booleans are dyadic functions, so the result of calling not with a Church Boolean should be a function with two arguments: that’s what “a” and “b” are for. The body of the function may look a bit weird: we’re calling “m” (a Church Boolean, but remember everything is a function hence &lt;em&gt;executable&lt;/em&gt;) with arguments b and a. That has a flipping effect as proven below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_12.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_12.png" width="534" height="110" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Impressive, isn’t it? A word on notation: before doing a beta-reduction we indicate the abstractions we’re going to apply substitutions for by putting a bar on top of them (e.g. in the second step m, in the fourth step x and y). When doing multiple reductions we write an arrow with a double arrowhead. When substituting terms for their definition (like T and F in the proof above), we carry out alpha-conversion to avoid the risk of name clashes (though strictly speaking for closed terms we could play a more risky game).&lt;/p&gt;

&lt;p&gt;How can we do binary operators, like and, or and xor? Turns out those are fairly simple to do as well:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;and = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(m =&amp;gt; n =&amp;gt; m(n)(m));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;or = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(m =&amp;gt; n =&amp;gt; m(m)(n));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;xor = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;&amp;gt;(m =&amp;gt; n =&amp;gt; a =&amp;gt; b =&amp;gt; m(n(b)(a))(n(a)(b)));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Agreed, one needs to see a proof of correctness before being convinced those functions have the desired behavior. By the way, outside C#, we could save us some parentheses which mainly come from (dynamic) delegate invocations above. Also notice that the functions for and and or don’t have abstractions in their “body”: the result of calling “mnm” or “mmn” already gives a function of the right arity, as can be seen in the proofs below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_13.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_13.png" width="427" height="299" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The proof for xor is left as an exercise to the reader (feel free to use case analysis of all four combinations of arguments, although you can simplify matters a bit…).&lt;/p&gt;

&lt;p&gt;Of course you want to see this in action. We already have our Unary function to test lambda functions with given arguments, let’s define a similar one for binary operators:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Binary&amp;lt;T, PArg, PRes&amp;gt;(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, T&amp;gt; f, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, PArg&amp;gt; printArg, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, PRes&amp;gt; printRes, &lt;span style="color:blue;"&gt;params dynamic&lt;/span&gt;[] values)
{
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;valueL &lt;span style="color:blue;"&gt;in &lt;/span&gt;values)
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;valueR &lt;span style="color:blue;"&gt;in &lt;/span&gt;values)
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;{0}({1}, {2}) = {3}&amp;quot;&lt;/span&gt;, name, printArg(valueL), printArg(valueR), printRes(f(valueL)(valueR)));
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;It basically creates all combinations of input arguments and applies them to the function, putting some pretty printing to the mix. So we write:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Church Booleans&amp;quot;&lt;/span&gt;);
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;toBool&amp;quot;&lt;/span&gt;, toBool, toBool, I, F, T);
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;not&amp;quot;&lt;/span&gt;, not, toBool, toBool, F, T);
Binary(&lt;span style="color:#a31515;"&gt;&amp;quot;and&amp;quot;&lt;/span&gt;, and, toBool, toBool, F, T);
Binary(&lt;span style="color:#a31515;"&gt;&amp;quot;or&amp;quot;&lt;/span&gt;, or, toBool, toBool, F, T);
Binary(&lt;span style="color:#a31515;"&gt;&amp;quot;xor&amp;quot;&lt;/span&gt;, xor, toBool, toBool, F, T);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The use of toBool allows us to go from a “dynamic” function to a concrete C# Boolean value which is printable by Console.WriteLine. The result looks like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_14.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_14.png" width="677" height="258" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Looks right, doesn’t it?&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Church numerals&lt;/h1&gt;

&lt;p&gt;If we can do Booleans, we can do numeric values too, right? Let’s restrict ourselves to positive natural numbers (including 0) and we end up with the concept of Church numerals. Now we have an infinite domain of values to represent, we need a way to control this complexity somehow (in order to be able to define nice operators over them). One possible solution is the use of repeated function application to encode a numeric value, as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_15.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_15.png" width="362" height="137" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Can you see it? Calling f on argument x once corresponds to 1, twice corresponds to 2, etc. Quite nice. What kind of simple operations can we define over such value representation? Clearly we don’t want to define all different N-objects for the whole domain of natural numbers. In fact, we don’t even want to define N1 explicitly. Two basic ingredients should suffice to define every natural number: a representation of 0, and a way to “add one” to a Church numeral (i.e. returning a new function that represents the value of the argument, plus one). This is the much desired successor function:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;N0 = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(f =&amp;gt; x =&amp;gt; x);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;succ = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;(n =&amp;gt; f =&amp;gt; x =&amp;gt; f(n(f)(x)));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The successor function is a function with one argument “n”, returning a function of two arguments “f” and “x” (like all Church numerals being double-abstractions over some term). The definition is “f(nfx)”, with some more parentheses in C#. But how does it work? See it with your own eyes and feed it N0 for starters: “n” is substituted (beta conversion) for “N0” which by itself is a lambda expression of the form shown in the figure above (goes from f and x to x). A few beta-conversions later you’ll end up with f(x), exactly the definition of N1. In other words, succ simply adds an additional “f” application to the existing term’s body. A more formal proof is given below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_16.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_16.png" width="901" height="119" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Based on this, can we create a simple conversions function to promote a C# positive integer value into a corresponding Church numeral? The answer is obviously yes and the idea is fairly easy: we’ll call succ repeatedly, n times for integer with value n, starting with N0 as the base. To go back from a Church numeral to a C# unsigned integer we exploit the repeated function call behavior on argument “f” and use a devilish side-effect to increment a counter whenever we are called:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;uint&lt;/span&gt;&amp;gt; toInt = x =&amp;gt;
{
    &lt;span style="color:blue;"&gt;uint &lt;/span&gt;n = 0;
    x(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(_ =&amp;gt; { n++; }))(&lt;span style="color:blue;"&gt;null&lt;/span&gt;);
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;n;
};

&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;uint&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt; fromInt = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;
fromInt = n =&amp;gt;
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;(n == 0 ? N0 : succ(fromInt(n - 1)));
};&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you don’t get this immediately, don’t worry. Just feed it some Church numerals and see what happens. For example, N0 is a function that simply returns its second argument. When calling toInt on N0, x is bound to N0, executed with two arguments of which the second one – null – is returned. The function of type Action&amp;lt;dynamic&amp;gt; in the first argument was never called, so the result is 0. But if N1 is fed in, that function in the first argument will get called how many times? Right, just one time. In other words, the side-effecting n++ will be called once, and the result is 1. In other words, we should be able to “roundtrip” C# integers through Church numerals:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;uint &lt;/span&gt;i = 0; i &amp;lt;= 10; i++)
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(toInt(fromInt(i)));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Try it at home and you should see the numbers 0 through 10 being printed on the screen. Victory. Oh, and fromInt is simply a recursive function that makes successor calls till n == 0 is reached, at which point N0 is returned. So, fromInt(5) will be encoded as succ(succ(succ(succ(succ(N0)))).&lt;/p&gt;

&lt;p&gt;All of this looks good, doesn’t it? Another useful function is a zero-test. In the typed world this would be a function from an integer to a Boolean, but of course in the world of type-free lambda calculus we loose that typing safety net. Nevertheless, here’s how zero looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;zero = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(n =&amp;gt; n(K(F))(T));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Recall that N0 was the same as F, and we know that F returns its second argument for its result. A zero-check on N0 clearly should return T, so the zero function should look like n (???) T. This satisfies the case where N0 is fed in. What about the other cases? Well, the first argument to n (the Church numeral passed in) is the function that gets called repeatedly on the second argument (which we already made T). For all those numerals we want to return F for the zero-check, so the question is whether we know a function that will always return F no matter what argument it’s given? We do, it’s called K with argument F: the constant-generator combinator K which we ask friendly to return hardheadedly F all the time. A formal proof is shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_17.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_17.png" width="885" height="118" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Finally, the real stuff. What about operations like add and multiply, or even exponential? The good thing is they exist indeed :-). And here they are:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;plus = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;&amp;gt;(m =&amp;gt; n =&amp;gt; f =&amp;gt; x =&amp;gt; m(f)(n(f)(x)));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;mul = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;(m =&amp;gt; n =&amp;gt; f =&amp;gt; n(m(f)));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;exp = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(m =&amp;gt; n =&amp;gt; n(m));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;How they work is another piece of cake. Here’s a proof for plus’s behavior:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_18.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_18.png" width="735" height="111" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That was fairly easy, wasn’t it? Feel free to feed it a couple of values to confirm the behavior, but we’ll run it through some tests in just a while. For mul and exp, proofs need some inductive reasoning as shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_19.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_19.png" width="961" height="535" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice how beautiful the definition of exp is: apply n with argument m, and you got an exponential. Wow. If I’d drink alcohol, this would be a reason to get drunk. I’ll stick with Diet Coke anyhow, but suffice to say I absolutely love it. And far that matter, mul is nice too, don’t you agree?&lt;/p&gt;

&lt;p&gt;What about a predecessor and subtract function? Unfortunately those are quite ugly in this Church numeral encoding system:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;pred = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;(n =&amp;gt; f =&amp;gt; x =&amp;gt; n(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(a =&amp;gt; b =&amp;gt; b(a(f))))(K(x))(I));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Bweik. It’s so disgusting I’ll leave the definition of a “sub” function (tip: use pred) to the reader. Oh, and if you’re really fearsome, prove the correctness of “pred” using induction.&lt;/p&gt;

&lt;p&gt;Anyway, here’s a test-application for Church numerals:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Church numerals&amp;quot;&lt;/span&gt;);
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;toInt&amp;quot;&lt;/span&gt;, toInt, toInt, I, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 3).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;succ&amp;quot;&lt;/span&gt;, succ, toInt, toInt, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 3).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;pred&amp;quot;&lt;/span&gt;, pred, toInt, toInt, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 3).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;zero&amp;quot;&lt;/span&gt;, zero, toInt, toBool, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 2).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
Binary(&lt;span style="color:#a31515;"&gt;&amp;quot;plus&amp;quot;&lt;/span&gt;, plus, toInt, toInt, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 3).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
Binary(&lt;span style="color:#a31515;"&gt;&amp;quot;mul&amp;quot;&lt;/span&gt;, mul, toInt, toInt, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 3).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
Binary(&lt;span style="color:#a31515;"&gt;&amp;quot;exp&amp;quot;&lt;/span&gt;, exp, toInt, toInt, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 3).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;We use our beloved fromInt function in combination with some LINQ operators to produce an array of test inputs, for which all combinations will be fed to the passed-in functions:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_20.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_20.png" width="677" height="522" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Wonderful. (Don’t bother to ask about performance…)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Going nuts – recursive functions&lt;/h1&gt;

&lt;p&gt;We could go much further and define pairs, tuples and lists using Church encodings as well, but as I have another rabbit in my hat for another time, I won’t spoil the beans at this point. A little sneak peak though (this is &lt;em&gt;without &lt;/em&gt;C# 4.0 dynamic…), for pairs:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;Pair = λ(x =&amp;gt; λ(y =&amp;gt; λ(z =&amp;gt; ß(ß(z, x), y)))); &lt;span style="color:green;"&gt;// \xyz.zxy
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;Fst = λ(p =&amp;gt; ß(p, T)); &lt;span style="color:green;"&gt;// \p.pT
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;Snd = λ(p =&amp;gt; ß(p, F)); &lt;span style="color:green;"&gt;// \p.pF&lt;/span&gt;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;and for lists:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;Nil = ß(ß(Pair, T), T);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;IsNil = Fst;
&lt;span style="color:blue;"&gt;var &lt;/span&gt;Cons = λ(h =&amp;gt; λ(t =&amp;gt; ß(ß(Pair, F), ß(ß(Pair, h), t))));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;Head = λ(z =&amp;gt; ß(Fst, ß(Snd, z)));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;Tail = λ(z =&amp;gt; ß(Snd, ß(Snd, z)));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Instead, let’s conclude this post with two recursive functions:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// The icing on the cake.
//
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt; Fix = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;
Fix = f =&amp;gt; x =&amp;gt; f(Fix(f))(x);

&lt;span style="color:blue;"&gt;var &lt;/span&gt;fact = Fix(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(f =&amp;gt; x =&amp;gt; zero(x)(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(_ =&amp;gt; succ(N0)))(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(_ =&amp;gt; mul(x)(f(pred(x)))))(I)));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;fib = Fix(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;&amp;gt;(f =&amp;gt; x =&amp;gt; zero(x)(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(_ =&amp;gt; N0))(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(_ =&amp;gt; zero(pred(x))(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(__ =&amp;gt; succ(N0)))(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(__ =&amp;gt; plus(f(pred(x)))(f(pred(pred(x))))))(I)))(I)));

Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;fact&amp;quot;&lt;/span&gt;, fact, toInt, toInt, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 10).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());
Unary(&lt;span style="color:#a31515;"&gt;&amp;quot;fib&amp;quot;&lt;/span&gt;, fib, toInt, toInt, &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 10).Select(i =&amp;gt; fromInt((&lt;span style="color:blue;"&gt;uint&lt;/span&gt;)i)).ToArray());&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This gets quite ugly due to the use of a &lt;a href="http://blogs.msdn.com/madst/archive/2007/05/11/recursive-lambda-expressions.aspx"&gt;fixpoint combinator&lt;/a&gt; and the chase to circumvent call-by-value semantics (exercise: where and how does that happen precisely in the fragments above?) causing endless evaluations (exhausting the stack), but rest assured those functions work just fine:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_21.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/FunwithTypeFreelambdaCalculusinC_8C3F/image_thumb_21.png" width="677" height="282" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Finally, an outtake :-). What does the following result in?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;Omega = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(x =&amp;gt; x(x))(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;, &lt;span style="color:blue;"&gt;dynamic&lt;/span&gt;&amp;gt;(x =&amp;gt; x(x)));
Omega(I);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Got a headache? Click &lt;a href="http://en.wikipedia.org/wiki/Aspirin"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14702" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Functional+programming/default.aspx">Functional programming</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx">Crazy Sundays</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>Introducing “The C# Ducktaper” – Bridging the dynamic world with the static world</title><link>http://blogs.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>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14070</wfw:commentRss><comments>http://blogs.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;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Dynamic&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;GetCallSite&amp;quot;&lt;/span&gt;, &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;string&lt;/span&gt;) }, &lt;span style="color:blue;"&gt;null&lt;/span&gt;));
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Stfld, callSiteField);

    &lt;span style="color:green;"&gt;//
    // Target of conditional jump in case call-site was already initialzed; fall-through otherwise.
    //
    &lt;/span&gt;methodILGen.MarkLabel(makeCall);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Recall our (simplistic) GetCallSite method on Dynamic? Here we call this one in case the current call site field is null. The generated IL goes as follows (_|_ stands for bottom of the stack frame, { … } indicates equivalent C# code executed at that point):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldarg_0&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, this&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldfld &lt;/font&gt;_site1&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, this._site 
        &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;brtrue &lt;/font&gt;MakeCall&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_&amp;#160; { if (this._site != null) goto MakeCall } 
        &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldarg_0&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, this 
        &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldarg_0&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, this, this 
        &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldstr&lt;/font&gt; “TargetMethod”&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, this, this, “TargetMethod” 
        &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;callvirt &lt;/font&gt;Dynamic.GetCallSite &lt;font color="#008000"&gt;// _|_, this, base.GetCallSite(“TargetMethod”) 
        &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;stfld &lt;/font&gt;_site1&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_&amp;#160; { this._site = base.GetCallSite(“TargetMethod”) } 
        &lt;br /&gt;&lt;/font&gt;

      &lt;br /&gt;MakeCall: 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; …&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Next comes the real work, where we pack up the arguments for the member call and dispatch to our Invoke delegate on the CallSite object. Recall the Invoke delegate is our source of major flexibility: here we yield control to the CallSite implementation to do whatever it sees fit to make the call as efficient as possible. For instance, if it comes to the conclusion you’re invoking a statically defined member on an object, there’s no good reason not to cache the invocation path, maybe on its turn by means of IL generation in a DynamicMethod. We’re lame though and just implement the bare minimum dispatch mechanism, but we still need to make sure we get there, so that’s where calling through the delegate comes in, continuing in our EmitMethod implementation. First we get the delegate:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// Func&amp;lt;object[], object&amp;gt; &amp;lt;invoke&amp;gt; = &amp;lt;callSiteField&amp;gt;.Invoke;
//
&lt;/span&gt;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;.Callvirt, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;CallSite&lt;/span&gt;).GetProperty(&lt;span style="color:#a31515;"&gt;&amp;quot;Invoke&amp;quot;&lt;/span&gt;).GetGetMethod());&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;or, in terms of the generated IL,&lt;/p&gt;

&lt;blockquote&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldarg_0&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, this&lt;/font&gt; 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldfld &lt;/font&gt;_site1&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, this._site 
      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;callvirt &lt;/font&gt;&lt;font color="#000000"&gt;get_Invoke&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font color="#008000"&gt;// _|_, base.Invoke 
        &lt;br /&gt;&lt;/font&gt;

      &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;/blockquote&gt;

&lt;p&gt;We even don’t store the delegate instance in a local variable and just keep it on top of our stack. Next we need to pack the arguments to our method in an object array that becomes the argument to the call through Invoke. This is a bit tricky as we might have value types that need to get boxed.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// object[] &amp;lt;args&amp;gt; = new object[&amp;lt;number_of_params&amp;gt;];
//
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LocalBuilder &lt;/span&gt;args = methodILGen.DeclareLocal(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;[]));
methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldc_I4, parameterTypes.Length);
methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Newarr, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;));
methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Stloc, args);

&lt;span style="color:green;"&gt;//
// &amp;lt;args&amp;gt;[0] = &amp;lt;param_1&amp;gt;;
// &amp;lt;args&amp;gt;[1] = &amp;lt;param_2&amp;gt;;
// ...
// &amp;lt;args&amp;gt;[n] = &amp;lt;param_n+1&amp;gt;;
//
&lt;/span&gt;&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0;
&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;paramType &lt;span style="color:blue;"&gt;in &lt;/span&gt;parameterTypes)
{
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldloc, args);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldc_I4, i);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg, i + 1);
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(paramType.IsValueType)
        methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Box, paramType);
    methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Stelem_Ref);
    i++;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;First we declare a local of type object[]. We need this one as we constantly need to load it to store the arguments in one-by-one in the foreach loop below. The dimension of the array is determined by the number of parameters on the member. For methods this count is trivial, for property setters this will include the “value” parameter but also all of the possible indexer arguments. However, we don’t see those complexities in EmitMethod, so I’ll elaborate on this a little further. The IL to create the array and store it in the local variable should be clear. Next we iterate over all of the parameters and implement code to fetch the corresponding argument from the current method call and stick it in the array. Notice the ldarg instruction:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg, i + 1); &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we use i + 1, as the first argument to the method call will be the this pointer and we don’t need that one as an argument to our dispatched method call. Another point of attention is the conditional emission of a boxing instruction when adding a value type to the parameters array. Here’s a typical run in IL including stack transitions, for a method call to Bar(string name, int age):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldc_i4 &lt;/font&gt;2&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, 2&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font color="#008000"&gt;// _|_, new object[2]&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;stloc &lt;/font&gt;args&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_ { args = new object[2] }&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldloc &lt;/font&gt;args&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, args&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldc_i4 &lt;/font&gt;0&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, args, 0&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldarg &lt;/font&gt;1&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, args, 0, name&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;stelem_ref&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_ { args[0] = name }&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldloc &lt;/font&gt;args&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, args&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldc_i4&lt;/font&gt; 1&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, args, 1&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldarg &lt;/font&gt;2&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_, args, 1, age&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;box&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font color="#008000"&gt;// _|_, args, 1, (object)age&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;stelem_ref&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// _|_ { args[1] = (object)age }&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we have packed up the arguments to the call, the next step is to call through the delegate to dispatch the call to the target method through the CallSite thunking mechanisms. The code to emit the IL is very simple:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// object &amp;lt;res&amp;gt; = &amp;lt;invoke&amp;gt;(&amp;lt;args&amp;gt;);
//
&lt;/span&gt;methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldloc, args);
methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Callvirt, &lt;span style="color:blue;"&gt;typeof&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;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Invoke&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;which simply calls the delegate’s Invoke method. Finally, if the method is not void-returning, we need to bubble up the return value to the caller, possibly unboxing the return value in case it’s a value type (as the delegate returns us an object). The pop instruction below is required to keep the stack balanced (in the case of ret from a void method):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;//
// return &amp;lt;res&amp;gt;;
//
&lt;/span&gt;&lt;span style="color:blue;"&gt;if &lt;/span&gt;(returnType != &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;void&lt;/span&gt;))
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(returnType.IsValueType)
        methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Unbox_Any, returnType);
}
&lt;span style="color:blue;"&gt;else
    &lt;/span&gt;methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Pop);

methodILGen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ret);

&lt;span style="color:blue;"&gt;return &lt;/span&gt;methodBuilder;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;That’s it – we now how our IL tool arsenal ready to dispatch any call to the underlying object.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;How to deal with properties and events&lt;/h1&gt;

&lt;p&gt;Properties and events are just a little more than regular methods – they also have metadata containing type information and references to the associated methods. If you wonder about indexers, they’re merely the same as properties but with additional arguments. As events are quite similar to properties, we’ll just stick with properties. In a top-down approach, we start by creating a PropertyBuilder:&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;propertyInfo&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;property&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;propertyInfo&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Property 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;ImplementInterfaceProperty(&lt;span style="color:#2b91af;"&gt;PropertyInfo &lt;/span&gt;propertyInfo, &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;//
    // Reconstruction of the signature.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;returnType = propertyInfo.PropertyType;
    &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] parameterTypes = propertyInfo.GetIndexParameters().Select(parameter =&amp;gt; parameter.ParameterType).ToArray();

    &lt;span style="color:green;"&gt;//
    // Get the full name for the member.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;string &lt;/span&gt;propertyName = GetTargetMemberName(propertyInfo);&lt;span style="color:green;"&gt;

    //
    // Define the property.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;PropertyBuilder &lt;/span&gt;propertyBuilder = typeBuilder.DefineProperty(propertyName, &lt;span style="color:#2b91af;"&gt;PropertyAttributes&lt;/span&gt;.None, returnType, parameterTypes);

    &lt;span style="color:green;"&gt;//
    // Getter.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;if &lt;/span&gt;(propertyInfo.CanRead)
        ImplementInterfacePropertyGetter(propertyInfo, typeBuilder, propertyBuilder, parameterTypes, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter);

    &lt;span style="color:green;"&gt;//
    // Setter.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;if &lt;/span&gt;(propertyInfo.CanWrite)
        ImplementInterfacePropertySetter(propertyInfo, typeBuilder, propertyBuilder, parameterTypes, &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;First we determine the “signature of the property”, which is relevant for indexed properties (indexers in C# lingo). Next, we perform the mapping between the interface member and the underlying property name to dispatch to. In the regular case this will be a one-on-one mapping, but using TargetMemberAttribute one can change that default:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;span style="color:blue;"&gt;&lt;font face="Courier new"&gt;public interface &lt;/font&gt;&lt;/span&gt;&lt;font face="Courier new"&gt;&lt;span style="color:#2b91af;"&gt;IFoo 
        &lt;br /&gt;&lt;/span&gt;{ 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [&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;br /&gt;&amp;#160;&amp;#160;&amp;#160; &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;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;GetTargetMemberName is the one that performs this mapping resolution using custom attributes. Finally we define the property and add a getter and/or setter to it depending on what the interface requires. Here we get in the terrain of our old EmitMethod friend, but with some intermediate work left to do in order to resolve the underlying method name (like get_, set_, etc):&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 the method definition for a property getter.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;propertyInfo&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Property to generate a property getter 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;propertyBuilder&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Property builder to associate the getter method with.&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;Parameters used for indexed properties, or an empty array for regular properties.&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;ImplementInterfacePropertyGetter(&lt;span style="color:#2b91af;"&gt;PropertyInfo &lt;/span&gt;propertyInfo, &lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder, &lt;span style="color:#2b91af;"&gt;PropertyBuilder &lt;/span&gt;propertyBuilder, &lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] parameterTypes, &lt;span style="color:blue;"&gt;ref int &lt;/span&gt;siteCounter)
{
    &lt;span style="color:blue;"&gt;const string &lt;/span&gt;GETPREFIX = &lt;span style="color:#a31515;"&gt;&amp;quot;get_&amp;quot;&lt;/span&gt;;

    &lt;span style="color:green;"&gt;//
    // Get thunk-to-target name mapping.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;string &lt;/span&gt;methodName;
    &lt;span style="color:blue;"&gt;string &lt;/span&gt;targetMethodName;
    GetMethodNamesForThunkAndTarget(propertyInfo, GETPREFIX, &lt;span style="color:blue;"&gt;out &lt;/span&gt;methodName, &lt;span style="color:blue;"&gt;out &lt;/span&gt;targetMethodName);

    &lt;span style="color:green;"&gt;//
    // Emit the getter.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodBuilder &lt;/span&gt;methodBuilder = EmitMethod(typeBuilder, methodName, parameterTypes, propertyBuilder.PropertyType, targetMethodName, &lt;span style="color:blue;"&gt;ref &lt;/span&gt;siteCounter, &lt;span style="color:blue;"&gt;true&lt;/span&gt;);

    &lt;span style="color:green;"&gt;//
    // Set the getter.
    //
    &lt;/span&gt;propertyBuilder.SetGetMethod(methodBuilder);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The only piece of glue here is a method called GetMethodNamesForThunkAndTarget that constructs the names of both the source method (e.g. get_Price, on the interface) and the target method (e.g. get_UnitPrice, on the target object). One other relevant thing here is the last parameter to EmitMethod, which is set to true, indicating the fact the emitted method is a “special name” one.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;What’s the result?&lt;/h1&gt;

&lt;p&gt;To make all this IL voodoo concrete, here’s the corresponding C# code for the class generated on our original sample:&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;becomes&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 = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&amp;lt;&amp;gt;__Thunks.&lt;font color="#008080"&gt;IDuck&lt;/font&gt;(dynamicDuck);&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;where&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;namespace &lt;/font&gt;&amp;lt;&amp;gt;__Thunks 

      &lt;br /&gt;{ 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public sealed class &lt;/font&gt;&lt;font color="#008080"&gt;IDuck&lt;/font&gt; : &lt;font color="#008080"&gt;Dynamic&lt;/font&gt;, TheNamespaceWhereIDuckLives.&lt;font color="#008080"&gt;IDuck&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; { 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;IDuck(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o) : &lt;font color="#0000ff"&gt;base&lt;/font&gt;(o) { } 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;CallSite &lt;/font&gt;_site1; 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public void &lt;/font&gt;Walk() 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; { 

      &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; &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;&amp;#160;&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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site1.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[0]); 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;CallSite &lt;/font&gt;_site2; 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public void &lt;/font&gt;Walk(&lt;font color="#0000ff"&gt;int&lt;/font&gt; steps) 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; { 

      &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; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(_site2 == &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site2 = &lt;font color="#0000ff"&gt;base&lt;/font&gt;.GetCallSite(&lt;font color="#800000"&gt;“Walk”&lt;/font&gt;); 

      &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; _site2.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[] { steps }); 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;CallSite &lt;/font&gt;_site3; 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public object &lt;/font&gt;Quack(&lt;font color="#0000ff"&gt;string &lt;/font&gt;name) 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; { 

      &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; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(_site3 == &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site3 = &lt;font color="#0000ff"&gt;base&lt;/font&gt;.GetCallSite(&lt;font color="#800000"&gt;“Quack”&lt;/font&gt;); 

      &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; &lt;font color="#0000ff"&gt;return &lt;/font&gt;_site3.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[] { name }); 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;CallSite &lt;/font&gt;_site4; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;CallSite &lt;/font&gt;_site5; 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;ConsoleColor &lt;/font&gt;Color 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; { 

      &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; &lt;font color="#0000ff"&gt;get&lt;/font&gt; 

      &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; { 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(_site4 == &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site4 = &lt;font color="#0000ff"&gt;base&lt;/font&gt;.GetCallSite(&lt;font color="#800000"&gt;“get_Color”&lt;/font&gt;); 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;_site4.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[0]); 

      &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; } 

      &lt;br /&gt;

      &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; &lt;font color="#0000ff"&gt;set&lt;/font&gt; 

      &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; { 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(_site5 == &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site5 = &lt;font color="#0000ff"&gt;base&lt;/font&gt;.GetCallSite(&lt;font color="#800000"&gt;“set_Color”&lt;/font&gt;); 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return (&lt;font color="#008080"&gt;ConsoleColor&lt;/font&gt;)&lt;/font&gt;_site5.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;value&lt;/font&gt; }); 

      &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; } 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;CallSite &lt;/font&gt;_site6; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;CallSite &lt;/font&gt;_site7; 

      &lt;br /&gt;

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;EventHandler &lt;/font&gt;&lt;font color="#333333"&gt;Walking&lt;/font&gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; { 

      &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; &lt;font color="#0000ff"&gt;add&lt;/font&gt; 

      &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; { 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(_site6 == &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site6 = &lt;font color="#0000ff"&gt;base&lt;/font&gt;.GetCallSite(&lt;font color="#800000"&gt;“add_Walking”&lt;/font&gt;); 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site6.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;value&lt;/font&gt; }); 

      &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; } 

      &lt;br /&gt;

      &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; &lt;font color="#0000ff"&gt;remove&lt;/font&gt; 

      &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; { 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(_site7 == &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site7 = &lt;font color="#0000ff"&gt;base&lt;/font&gt;.GetCallSite(&lt;font color="#800000"&gt;“remove_Walking”&lt;/font&gt;); 

      &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;&amp;#160;&amp;#160;&amp;#160;&amp;#160; _site7.Invoke(&lt;font color="#0000ff"&gt;new object&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;value&lt;/font&gt; }); 

      &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; } 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; } 

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;How’s performance doing?&lt;/h1&gt;

&lt;p&gt;Now that we have our new toy, time to evaluate how we’re doing at this stage from a performance point of view. Before we discuss though, it’s important to emphasize the fact we’re focusing on a &lt;em&gt;dynamic&lt;/em&gt; casting operation, i.e. it should work regardless of the object passed in (assuming that method implements the right members). What we have now is a degenerate case though, where we have CallSites that are only aware about the possibility to dispatch to a static type in a late-bound way. Additional tests, such as checking for expandos or IDynamicObjects, would be required to get the desired level of flexibility and will definitely incur a runtime cost. However, with our simplified code we can set a baseline on what to expect.&lt;/p&gt;

&lt;p&gt;Here’s a very simple test that compares the performance of calling through a vtable directly based on static type knowledge, versus dispatching through our duck taper:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static void &lt;/span&gt;TestDucks()
{
    MeasureDuckPerformance(&lt;span style="color:#a31515;"&gt;&amp;quot;Static duck&amp;quot;&lt;/span&gt;, () =&amp;gt; &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Duck2&lt;/span&gt;());
    MeasureDuckPerformance(&lt;span style="color:#a31515;"&gt;&amp;quot;Dynamic duck&amp;quot;&lt;/span&gt;, () =&amp;gt; GetDuck().AsIf&amp;lt;&lt;span style="color:#2b91af;"&gt;IDuck&lt;/span&gt;&amp;gt;());
}

&lt;span style="color:blue;"&gt;static void &lt;/span&gt;MeasureDuckPerformance(&lt;span style="color:blue;"&gt;string &lt;/span&gt;description, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IDuck&lt;/span&gt;&amp;gt; duckGetter)
{
    &lt;span style="color:#2b91af;"&gt;TimeSpan &lt;/span&gt;performance = DuckTest(duckGetter, 10000, duck =&amp;gt;
    {
        duck.Color = &lt;span style="color:#2b91af;"&gt;ConsoleColor&lt;/span&gt;.Blue;
        duck.Walking += duck_Walking;
        duck.Walk();
        duck.Quack(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;);
        duck.Walk(3);
        duck.Walking -= duck_Walking;
    });

    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(description + &lt;span style="color:#a31515;"&gt;&amp;quot;: &amp;quot; &lt;/span&gt;+ performance);
}

&lt;span style="color:blue;"&gt;static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;TimeSpan &lt;/span&gt;DuckTest(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IDuck&lt;/span&gt;&amp;gt; duckGetter, &lt;span style="color:blue;"&gt;int &lt;/span&gt;count, &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IDuck&lt;/span&gt;&amp;gt; duckTest)
{
    &lt;span style="color:#2b91af;"&gt;IDuck &lt;/span&gt;duck = duckGetter();

    &lt;span style="color:#2b91af;"&gt;Stopwatch &lt;/span&gt;sw = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Stopwatch&lt;/span&gt;();
    sw.Start();
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; count; i++)
        duckTest(duck);
    sw.Stop();

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;sw.Elapsed;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The results looks as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;Dynamic duck: 00:00:01.1504488
      &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;Static duck: 00:00:02.2274213&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A factor two the difference, not too bad after all. This should be enough to satisfy our curiosity around dynamic dispatch mechanisms. There’s a lot of additional possibilities here, ranging from controlling dispatch behavior (early or late binding), optimizing with caching strategies, and so on. In future posts I might delve into the details of more flexible dispatching mechanisms, advanced ways to do caching and the technique of implementing “fast paths”. But then I might as well start talking about the crossroads where DLR and C# 4.0 meet, and we’re back to our promise: “why &lt;u&gt;this&lt;/u&gt; is &lt;em&gt;not&lt;/em&gt; a C# 4.0 blog post”.&lt;/p&gt;

&lt;p&gt;Have fun!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14070" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>“The C# Programming Language Third Edition” and thoughts on language evolution</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2008/10/19/the-c-programming-language-third-edition-and-thoughts-on-language-evolution.aspx</link><pubDate>Mon, 20 Oct 2008 02:22:53 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14000</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14000</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2008/10/19/the-c-programming-language-third-edition-and-thoughts-on-language-evolution.aspx#comments</comments><description>&lt;p&gt;With a &lt;a href="http://blogs.msdn.com/ericlippert/archive/2008/10/08/the-future-of-c-part-one.aspx"&gt;hypothetical next release&lt;/a&gt; of the C# language around the corner (more about that after Anders, our language Caesar, has delivered his “Future of C#” talk on the PDC 08), I’ve had the honor to receive an early print of &lt;a href="http://www.amazon.com/Programming-Language-Microsoft-NET-Development/dp/0321562992/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1224403716&amp;amp;sr=8-1"&gt;The C# Programming Language Third Edition&lt;/a&gt;. As you can guess, this book is the successor to &lt;a href="http://www.amazon.com/Programming-Language-Anders-Wiltamuth-Hejlsberg/dp/B001E034X0/ref=sr_1_2?ie=UTF8&amp;amp;s=books&amp;amp;qid=1224403716&amp;amp;sr=8-2"&gt;The C# Programming Language Second Edition&lt;/a&gt;, now extended with coverage for the C# 3.0 features and based on the unified &lt;a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc"&gt;C# Language Specification 3.0&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;So why would you want to buy a language specification in book format? Personally I like to have those things in print on my desk, just like I have &lt;a href="http://www.amazon.com/Language-Infrastructure-Annotated-Microsoft-Development/dp/0321154932"&gt;The Common Language Infrastructure Annotated Standard&lt;/a&gt; on my desk (unfortunately lagging behind a bit on &lt;a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm"&gt;ECMA 335&lt;/a&gt;). But there’s more to it with this new edition of the book: it got &lt;strong&gt;annotated&lt;/strong&gt; by a bunch of people, providing additional insights about the different language features, design decisions, consequences of those decisions, best practices on when and how to use certain features, etc. In other words, if you like to have the ultimate coverage of the C# language (&lt;em&gt;not&lt;/em&gt; its uses through certain tools using certain libraries) but don’t want to be bored to death by language specification &lt;em&gt;legalese&lt;/em&gt;, this book is for you. The annotations are numerous, enlightening and by times funny.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Some language history&lt;/h1&gt;  &lt;p&gt;Talking about language evolution, people often raise the question where the language is going with all those new fancy features. Doesn’t it become too bloated? Well, every new feature definitely ages the language (quoting Anders here) and some of the original features are ready for the graveyard because they got superseded by newer more powerful features. And yes, having more features means there’s more to learn when approaching the language. But at the same time, one shouldn’t forget about the core value of a language: capturing common paradigms and patterns, making them easier to use (expressiveness) and less error-prone. A few samples to illustrate this point.&lt;/p&gt;  &lt;p&gt;Starting with C# 1.0, one of the common design themes of the language was what I’d call “&lt;strong&gt;honesty and pragmatism&lt;/strong&gt;”. Programmers were talking all the time about e.g. properties, events and function pointers, so why shouldn’t these concepts become constructs directly available in the language? Such observations not only shaped the language but the underlying runtime as well, resulting in first-class support for metadata everywhere (well, almost everywhere). Pragmatic, yes, but honest? Sure enough. Although strictly speaking concepts like properties are foreign to &lt;em&gt;minimalistic &lt;/em&gt;object-oriented programming (yes, you can mimic function pointers by one-method-interfaces, and events can be simulated by likewise means), sprinkling a little bit of syntactical sugar and equally important metadata on top provides great benefits with regards to code understandability, tooling and runtime metadata inspection features (known as reflection). But this was only the beginning, as the “Cool” (&lt;em&gt;C-style object oriented language&lt;/em&gt;) language also embraced and captured common patterns such as iteration (foreach), proper handling of resources (using), resource locking (lock), etc. Nevertheless, there have always been features that are very powerful but shouldn’t be abused or misused, such as operator overloading, unsafe code, … And of course, the language doesn’t expose all of the underlying runtime’s features such as – just to name a few, there are many more – tail calls, typed references and arglists (&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx"&gt;somehow that sounds familiar&lt;/a&gt;).&lt;/p&gt;  &lt;p&gt;In C# 2.0, &lt;strong&gt;generics&lt;/strong&gt; were introduced, making the “Cup &lt;em&gt;of T&lt;/em&gt;” approach for collections (and more) a first-class citizen in the runtime and language, resulting in less errors and various other benefits (performance, richer IntelliSense, etc). At the same time, generics made previous “features” (partially) redundant. To point out one of these cases, refer to section 8.8.4 in the book you’re about to buy, covering the foreach loop. Before we had IEnumerable&amp;lt;T&amp;gt;, foreach had to deal with the non-generic counterpart resulting in quite some interesting complications that have to do with boxing and the use of casts on the iteration variable (as developers typically would like to iterate over the collection using a type more specific than System.Object, but there were no generics to give guarantees about the collection’s element type). This is a sample of where a new feature solves known problems while also opening the gateway to lots of new things that weren’t possible before. One such thing is a generalization of “nullability”, the lack of which has plagued many developers before when dealing with database records where the distinction between value and reference types doesn’t exist typically. Looking at the nullable type feature in C# 2.0, again the common theme of making common tasks easier pops up, while solving subtle shortcomings of previous releases, in this particular case with the unified type system lacking nullability for value types (a more fundamental “issue” that has quite some language impact, e.g. the use of the &lt;em&gt;default &lt;/em&gt;keyword when dealing with generics, more cases to consider in the generics constraint mechanism, etc).&lt;/p&gt;  &lt;p&gt;Although C# 2.0 was mostly about catching up on original design plans, there was also room for some innovation. I don’t know precisely when the idea about iterators came up, but these were definitely one of the more exotic features in the second release of the language, opening for lots of new possibilities. While standing on the shoulders of giants (in this case generics), newer language features start building again upon these (as you can guess I’m referring to LINQ to Objects, heavily relying on iterators). One especially notable thing about the C# 2.0 release was its dependence on new runtime-level features to support generics (&lt;a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm"&gt;ECMA 335&lt;/a&gt; and &lt;a href="http://www.ecma-international.org/publications/techreports/E-TR-089.htm"&gt;TR/89&lt;/a&gt;), so there’s no “&lt;a&gt;Lost in translation&lt;/a&gt;” C#-2.0-to-1.0 approach possible. And again, the language didn’t expose the underlying empowering runtime mechanism fully, namely with regards to generics &lt;a href="http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx"&gt;variance&lt;/a&gt; (ECMA 335 II.9.5).&lt;/p&gt;  &lt;p&gt;Our latest release so far, C# 3.0, followed the same principles but was really the first one to innovate or revolutionize the way we develop typical applications, whether it’s in the business domain (first class data querying with &lt;strong&gt;LINQ&lt;/strong&gt;), in a scientific atmosphere (lambda BLOCKED EXPRESSION or to enter the New World of Meta Programming (expression trees). Once more, features from previous releases, such as generics and iterators, become increasingly important to build newer features on. Radically different from C# 1.0 to 2.0, no runtime extensions were needed, allowing for a real “&lt;a&gt;Lost in translation&lt;/a&gt;” translation from C# 3.0 onto equivalent C# 2.0 constructs (not saying anything about readability of such a translation’s result though). Again in the realm of &lt;strong&gt;simplifying programming&lt;/strong&gt;, other constructs like auto-implemented properties and local variable type type inference were introduced, giving the language a more dynamic feeling while keeping strong-typing all the way through. Silly complexities to new up objects or collections were eliminated with new initializer syntaxes and specifying functions does no longer require noisy keywords like “delegate” (referring to the use in anonymous methods) thanks to lambda syntax. And while I admit that some of the syntax looks foreign, most of it can be understood straight away (maybe the only exception is the lambda arrow that requires one aha-erlebnis), so readability doesn’t suffer. As usual, features can get abused just like a Swiss knife is a powerful tool but can be used for bad purposes too. Samples include &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/23/appropriate-use-of-local-variable-type-inference.aspx"&gt;over-use of local variable type inference&lt;/a&gt; at the cost of readability, or inappropriate use of extension methods.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;A changing landscape&lt;/h1&gt;  &lt;p&gt;Languages (especially general-purpose ones) need to adapt to a changing programming landscape if they want to stay relevant. And while specialized domains hugely benefit from non-general purpose languages (not to use words like DSLs just yet) – and a mixed-language approach to solving problems is entirely possible thanks to the CLS – some concepts that used to be exotic or irrelevant are becoming mainstream for the first time (or again after being doomed dead a while ago). One such first-timer is &lt;strong&gt;functional &lt;em&gt;style&lt;/em&gt; of programming&lt;/strong&gt;. I’m deliberately highlighting the word style as I’m not referring to extremist functional programming (lazy evaluation, no side-effects, use of monads) but rather to influences originating from functional languages and all the underlying theory making their way into mainstream languages. C# 2.0 introduced the glue with true closures, C# 3.0 provided easier syntax with lambdas. And those investments have already paid off hugely with the advent of libraries like the Task Parallel Library and various LINQ implementations. In some sense, LINQ’s mission brought more &lt;em&gt;clarity &lt;/em&gt;(insider’s joke)&lt;em&gt; &lt;/em&gt;to the concurrency domain, almost as a &lt;em&gt;side-effect&lt;/em&gt; :-).&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Concurrency&lt;/strong&gt; is huge; Anders called it the elephant in the room in his &lt;a href="http://blog.jaoo.dk/2008/10/07/the-future-of-programming-languages/"&gt;JAOO talk&lt;/a&gt; (actually our hypothetical new version got a name in an &lt;a href="http://blog.jaoo.dk/2008/09/29/linqin-up-with-anders-hejlsberg/"&gt;interview with Anders on JAOO&lt;/a&gt;, I promise you the name won’t be a big surprise…). It has many faces, spreading from one machine to multiple machines, impacting not only the languages but also the way libraries are built and programs are written. Not to talk about tool support, operating system level changes, and the subtle interactions with hypervisor technologies (VM guests that want to benefit from multiple cores, trying not to collide with one another, etc). So there’s lots of work to be done in this domain to shape languages and tackle the beast. It doesn’t come for free though and things will have to give in: shifting from imperative style to a more &lt;strong&gt;declarative&lt;/strong&gt; style, giving up on “mutable data structures everywhere” (notice the placing of the quotes), etc. Essentially sharing knowledge about the problem at hand with the runtime, rather than over-specifying a particular approach to solve the problem.&lt;/p&gt;  &lt;p&gt;But there are other things going on as well, more specifically in the camp of &lt;strong&gt;dynamic languages and libraries&lt;/strong&gt;. Call it the Python or Ruby movement if you want. Several years ago it felt as if the importance of dynamic languages was decreasing but several factors have given them a boost once more. First of all there’s the productivity gain by using interactive editors and consoles: fast prototyping, script-driven development, etc. For that same reason, Windows PowerShell has become so popular and all of the benefits from dynamic languages are apparent in PowerShell: interactively investigating the system as you go, scripting support, a rich and extensible type system (ETS, get-member), and more to come with v2.0 (mobile types for remoting to name just one feature). Actually Windows PowerShell proves that reaching out to statically typed libraries from a dynamic world is incredibly easy, and so do F#, IronPython and IronRuby, all bringing the huge .NET Framework libraries in reach within the dynamic world (F# shares some of the dynamic characteristics such as an interactive console, but just has a huge amount of type inferencing that helps to decrease the verbosity of statically typed languages). But what about the reverse operation, calling dynamic libraries from a statically typed world? Why would one want to do such a thing you might wonder? For one, there are huge useful libraries in that camp too, so why should one not be able to reach out to these? But there’s more, with the increasingly popular web/cloud-oriented software approach, code gets surrounded more and more by a dynamic sea: JavaScript, AJAX, REST, etc all have dynamic characteristics while platforms like Silverlight are floating around in that sea, embedded in web pages. Having easy interop facilities between both worlds is therefore becoming increasingly important and relevant. Think of it as reversing the arrow in “talking from DLR to CLR is easy”.&lt;/p&gt;  &lt;p&gt;Finally, I’d point out a third source of language potential: the &lt;strong&gt;meta-programming paradigm&lt;/strong&gt;. It’s maybe the least understood and most ill-defined of the three, but domain specific islands within general-purpose environments (not to just say languages) have an enormous potential, if not abused. Environments like PowerShell have first-class support for regular expressions (-match operator), C# 3.0 and VB 9.0 have LINQ, but what about giving developers the means to cook their own DSLs when appropriate? Here we enter the realm of expression, statement and declaration trees (as implemented in the DLR), running compilers as services (CodeDOM and complete-program source compiler invocations – as in ASP.NET code behind – were the first, albeit degenerate and brute force approach, glimpse of this technique; later followed by LambdaExpression.Compile). Fluent interfaces can be seen as the poor man’s DSLs and going beyond that with &lt;a href="http://martinfowler.com/dslwip/InternalOverview.html"&gt;Internal DSLs&lt;/a&gt; is something that might prove useful in the future. Some people have (and still) bet on AOP as the new big paradigm after OO. Well, I’d put more bets on MP if I get to choose. While it’s not incompatible with ideas from OO, it has the potential of adding another dimension to programming. We already have a spatial extent with data-driven (OO) and operation-driven (procedural and functional) decomposition axes; MP could add a dimension to this picture, in the form of specialized problem space islands within a bigger language. Whether or not it’s really orthogonal is a question we’ll leave open for the time being…&lt;/p&gt;  &lt;p&gt;Future will tell, and part of that future is coming at PDC 08. Enjoy!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14000" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Functional+programming/default.aspx">Functional programming</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Intermezzo: SOS in Visual Studio</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/29/to-bind-or-not-to-bind-dynamic-expression-trees-intermezzo-sos-in-visual-studio.aspx</link><pubDate>Fri, 29 Aug 2008 10:05:16 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13929</guid><dc:creator>bart</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13929</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/29/to-bind-or-not-to-bind-dynamic-expression-trees-intermezzo-sos-in-visual-studio.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Last time we talked about dealing with dynamic code generation using Reflection.Emit to generate calls to our dynamic binder. I’ve shown how to see the IL that gets generated by means of the Dynamic IL Visualizer add-in in Visual Studio. In this post I want to point out that you can actually live without that visualizer and go the &lt;strong&gt;hard-core way using SOS&lt;/strong&gt;, aka “Son of Strike”, the WinDbg extension for managed code debugging that ships with the .NET Framework (sos.dll). A little-known fact is that SOS can be loaded directly in Visual Studio through the Immediate Window.&lt;/p&gt;  &lt;p&gt;&lt;u&gt;Note:&lt;/u&gt; This post is screenshot-driven; to conserve bandwidth I’ve included only thumbnails in the post itself; “click to enlarge” is the message.&lt;/p&gt;  &lt;p&gt;&lt;u&gt;Note:&lt;/u&gt; There are many ways to get to the information you care about; in the end we’re dealing with object graphs. This post is more an exploration of the data that you can get at if you want to do so; the various paths to get there are more a matter of style (in physical terms: the potential energy is constant, but the accumulated kinetic energy corresponding to the developer’s finger muscle contractions when dealing with the keyboard may vary).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 1 – Loading SOS&lt;/h1&gt;  &lt;p&gt;We’re on a breakpoint in managed code and will try to load SOS through the Immediate Window using &lt;em&gt;.load sos&lt;/em&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;For this to work, &lt;u&gt;native&lt;/u&gt; code debugging needs to be enabled in the project properties:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_3.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="176" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_3.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 2 – Finding dynamic methods&lt;/h1&gt;  &lt;p&gt;To find the dynamically generated methods, we can search the heap for objects of type DynamicMethod using &lt;em&gt;.dumpheap DynamicMethod&lt;/em&gt;. As you can see we don’t have any yet:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_4.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_4.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Using F10 we step to the next method, executing Compile causing the dynamic method for the expression to be compiled. Rerunning the command now yields:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_5.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_5.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We’re in business. As you can see we had two matching types: DynamicMethod and DynamicMethod+RTDynamicMethod. We’re interested in the former one, so we follow the MT field back to the list of objects. MT stands for Method Table which is a runtime structure describing the object layout for a particular type. It can be used to locate fields and methods in preparation to calls. If you want, you can use &lt;em&gt;!dumpmt –MD &amp;lt;MT address&amp;gt;&lt;/em&gt; to dump such a table; this will show all of the “methods in the table”.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 3 – Dumping the IL&lt;/h1&gt;  &lt;p&gt;Now that we have the DynamicMethod object, we can dump the IL for it using &lt;em&gt;!dumpIL &amp;lt;object address&amp;gt;&lt;/em&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_6.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_6.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As we were compiling the identity function I, the IL shown should just be a ldarg.0 and sure it is.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 4 – Another sample&lt;/h1&gt;  &lt;p&gt;We could have stopped with the previous sample but our dynamic dispatch is interesting to analyze too. Breaking after our Substring sample compilation (in a fresh run, so that the old DynamicMethod is no longer displayed) results in:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_7.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_7.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;We can follow it through to the IL again:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_8.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="145" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_8.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice the call to “something in parentheses”. This is the runtime token representing the method, which we can dump using &lt;em&gt;!do &amp;lt;address&amp;gt;&lt;/em&gt;. In addition, &lt;em&gt;!dumpIL&lt;/em&gt; hints at dumping the token array:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_9.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_9.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The result of doing so is an array of tokens used in the IL stream. I’ll show this in a second but you might wonder what those fancy numbers in the IL stream like “70000002” stand for. Those indicate token types as defined in CorTokenType (see corhdr.h, for instance in the SSCLI “Rotor” distribution). To find the token type, mask with 0xFF000000, so in our sample that leaves 0x&lt;strong&gt;70&lt;/strong&gt;000000 and this is defined as mdtString. The remainder (mask with 0x00FFFFFF) leaves us with the RID (relative ID) of 0x0000000&lt;strong&gt;2&lt;/strong&gt;, so entry two in the table contains the corresponding token value:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_10.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_10.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;And yes, we see “Substring” appearing. Similarly value 2000003 in IL_0010 gives us a type def token (for System.Object) at offset 3 and value 0a000004 in IL_0031 gives us a member ref token (for our DynamicBinder.Call method) at offset 4. For the latter one, the debugger output gives you the indirection in between parentheses straight away:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_11.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_11.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;How convenient!&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 5 - From token to MethodInfo to DeclaringType&lt;/h1&gt;  &lt;p&gt;Next we can follow the object chains all the way up to the declaring type: first we get from the token to the method it represents and second we can traverse m_declaringType to get the corresponding type:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_12.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_12.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This produces a System.RuntimeType instance containing a Method Table reference:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_13.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_13.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So we can dump the method table with &lt;em&gt;!dumpmt –MD &amp;lt;MT address&amp;gt;&lt;/em&gt; as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_14.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_14.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As you can see we’re in our DynamicBinder class.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 6 – What about the signature?&lt;/h1&gt;  &lt;p&gt;Instead of following the path to the m_declaringType above, we could follow the m_signature as well:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_15.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;System.Signature wraps a m_signature field of type SignatureStruct which we can dump as well, but as this is a value type we can’t use &lt;em&gt;!do&lt;/em&gt; but rather need to use &lt;em&gt;!dumpvc&lt;/em&gt; (standing for value class) passing in the method table (otherwise the debugger wouldn’t know how to interpret the struct which is simply a blob of data) and the address.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 7 – And back to the method being called&lt;/h1&gt;  &lt;p&gt;From the signature struct we can reach out to the method represented by the signature through m_pMethod. This is a runtime handle, wrapping an IntPtr pointer to where the loaded IL code lives. In other words, we can invoke dumpIL on that address to see the contents of what turns out to be our DynamicBinder.Call method:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_16.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_15.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;(Notice the closure classes in the IL generated because of our C# 3.0 lambda expressions embedded in the LINQ query we use for method overload resolution.)&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 8 – Dynamic modules&lt;/h1&gt;  &lt;p&gt;Dynamic methods live in dynamic modules, so it would be interesting to see those. SOS comes to the rescue with &lt;em&gt;!dumpdomain&lt;/em&gt;.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_17.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_16.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Scroll down a bit and we get to see the dynamic modules. With some poking around it turns out that the last one is the one we’re looking for as it contains a multicast delegate, precisely what we&amp;#39;ve been generating. We can visualize it using &lt;em&gt;!dumpmodule –mt&lt;/em&gt; &lt;em&gt;&amp;lt;address&amp;gt;&lt;/em&gt; also showing the types that are referenced inside the module (that’s where we see the MulticastDelegate).&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_18.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_17.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Also notice the attribute saying “Reflection”. To see how the type definition (TypeDef) is indirected through a method table map (MethodTableMap), follow the arrows below. Green indicates the indexing and again the masked first two bytes of the green value indicate the CorTokenType, in this case a TypeDef. You can do the same exercise for the TypeRef (0x01000000) – follow the memory pointer and get the first (zero-based count obviously) element referred in there (it should read 24 e5 0f 79 as you can infer from the output produced by the debugger, considering little endian conversion).&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_19.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_18.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Unfortunately the defined type is marked as unloaded so we’re at a dead end – feel free to explore the Method Table for the type a bit further. In a similar way you can track down the loaded module with our DynamicBinder to do some explorations (also starting from &lt;em&gt;!dumpdomain&lt;/em&gt;):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_20.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_19.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Dumping the binder’s method table gives us:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_21.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_20.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Who still needs ILDASM or Reflector? :-)&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Step 9 – Walking the stack&lt;/h1&gt;  &lt;p&gt;To finish this post, I’d like to show how to dump the stack objects using &lt;em&gt;!dso&lt;/em&gt; to get to some of this information through yet an alternative route:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_22.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_21.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In green I’ve indicated the result of the dynamic call and what it corresponds to. However, the items in red indicate our (mysterious?) unloaded type once more. As you’ll see though, the IL is still available:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_23.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="160" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesI_2A92/image_thumb_22.png" width="244" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The result is predictable by now I guess.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=13929" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 3</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/28/to-bind-or-not-to-bind-dynamic-expression-trees-part-3.aspx</link><pubDate>Thu, 28 Aug 2008 17:35:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13925</guid><dc:creator>bart</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13925</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/28/to-bind-or-not-to-bind-dynamic-expression-trees-part-3.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Last time in this series we were able to compile a stunningly complex “dynamic lambda” x =&amp;gt; x – also known as I in the world of combinators – into IL code at runtime. As that’s not particularly useful, we want to move on to slightly more complex expressions like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;o = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;call = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Call(o, &lt;span style="color:#a31515;"&gt;&amp;quot;Substring&amp;quot;&lt;/span&gt;, a, b);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;func = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(call, o, a, b);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Or, in pretty print,&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(o, a, b) =&amp;gt; o.Substring(a, b)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Setting the scene&lt;/h1&gt;

&lt;p&gt;We explained how the translation of a dynamic expression tree takes place in general: as we traverse the tree, individual nodes are visited asking them to append code capturing the expression’s semantics to an IL stream, pushing a value on the stack that corresponds to the evaluated expression. The method that does this translation for every dynamic expression is called “Compile”:&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;Appends IL instructions to calculate the expression&amp;#39;s runtime value, putting it on top of the evaluation stack.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;ilgen&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;IL generator to append to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;ldArgs&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Lambda argument mappings.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;protected internal abstract void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;In here we’re using a simplified concept of “lambda parameters in scope” using &lt;em&gt;ldArgs&lt;/em&gt;, avoiding getting into slightly more complex techniques such as hoisting that are required for more involved expression trees. Previously you saw how to implement this method for ParameterDynamicExpression and LambdaDynamicExpression, respectively:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!ldArgs.ContainsKey(&lt;span style="color:blue;"&gt;this&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;Parameter expression &amp;quot; &lt;/span&gt;+ Name + &lt;span style="color:#a31515;"&gt;&amp;quot; is not in scope.&amp;quot;&lt;/span&gt;);

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg, ldArgs[&lt;span style="color:blue;"&gt;this&lt;/span&gt;]);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;and&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
{
    Body.Compile(ilgen, ldArgs);
    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ret);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Dynamic method calls and binders&lt;/h1&gt;

&lt;p&gt;For MethodCallExpression things are a bit more involved than for the expression types above. Before we start, remember the most important portion of the Compile method contract: leave one value on top of the stack that corresponds to the evaluated expression, in this case a method call. What does a method call consist of? Here are the ingredients:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt; Arguments { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Object { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
&lt;span style="color:blue;"&gt;public string &lt;/span&gt;Method { &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;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;As we’re seeing other DynamicExpression objects being referenced in here, it’s already clear we’ll have to evaluate those by recursively calling Compile. So, we could do something along the lines of:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;compile Object 
    &lt;br /&gt;foreach argument in Arguments 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; compile argument 

    &lt;br /&gt;call Method&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That’s the typical structure of a call site, pushing arguments on the stack including the object to invoke the method on. From a stack point of view: n + 1 arguments are pushed, where n is the number of arguments and 1 accounts for the instance to invoke the method one, and next all of those stack citizens are eaten by the method call, producing the single return value on top of the stack. This follows the contract of our Compile method.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;There’s a slight problem though: we can’t emit the call because we don’t know what type to invoke it one. The reason is well-known in the meantime: the Object nor the Arguments have strongly-typed information, so just given a string named “Method”, we can’t get the required method metadata to emit a call(virt) instruction. Bummer. But that’s the whole point of dynamic programming, delaying the decision about the executed method/function till runtime because the type might dynamically grow with new members (think of ETS in PowerShell as a sample of such a capability).&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;One way to solve this problem is to emit a bunch of reflection code to investigate the type of Object at runtime, do the same for all of the arguments, try to find a suitable method to call, etc etc. I shouldn’t explain how complicated this would become :-). There are lots of drawbacks to this: we’re baking in the whole dynamic call infrastructure into the call site and as we’re emitting all of that code, the odds to adapt it without having to recompile the code are off. This whole “locate a suitable method” algorithm could be made extensible too if we’re not emitting it into the generated code straight away. In other words, we want to get out of the IL generating business as soon as we can, and introduce a level of indirection. That particular kind of indirection is what we call a &lt;strong&gt;binder&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;So what’s a binder precisely? It’s simply a class that contains all the functionality to make well-formed decisions (based on certain desired semantics) about method calls (amongst other invocation mechanisms). Actually we have such a thing in the framework already: &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx"&gt;System.Reflection.Binder&lt;/a&gt;. As the documentation says:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Selects a member from a list of candidates, and performs type conversion from actual argument type to formal argument type.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The list of candidates is something that can be made extensible, allowing methods to be “imported” or “attached” to existing types at runtime. The type conversion clause in the sentence above outlines that the binder is responsible to take the actual passed in arguments (in our case weakly typed) and turn them into (i.e. casting) formal argument types that are suitable for consumption by the selected candidate method. The sample on MSDN for &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx"&gt;System.Reflection.Binder&lt;/a&gt; shows what it takes to implement such a beast. We’re not going to do that though, just to simplify matters a bit. As we’re only interested in method calls, we’ll just implement the bare minimum binder to get the job done and explained. Furthermore, we won’t spend time on implicit conversions for built-in types (like int to long) as the mentioned sample illustrates that already. Last but not least, generics are not brought in the equation either.&lt;/p&gt;

&lt;p&gt;Without further delay, let’s show a possible binder implementation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicBinder
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static object &lt;/span&gt;Call(&lt;span style="color:blue;"&gt;object &lt;/span&gt;@this, &lt;span style="color:blue;"&gt;string &lt;/span&gt;methodName, &lt;span style="color:blue;"&gt;params object&lt;/span&gt;[] args)
    {
        &lt;span style="color:green;"&gt;//
        // Here we&amp;#39;re going to be lazy for demo purposes only. Our overload resolution
        // will pick the first applicable method without applying &amp;quot;betterness&amp;quot; rules
        // as outlined in the C# specification (v2.0, section $7.4.2). We don&amp;#39;t care
        // about extension methods either (how could the namespace be brought in scope
        // in the context of an expression tree...?) nor other dynamic type extensions
        // such as IExpando (~ IMarshalEx) or e.g. PowerShell ETS.
        //

        &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;result = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;method &lt;span style="color:blue;"&gt;in &lt;/span&gt;@this.GetType().GetMethods()
                      &lt;span style="color:blue;"&gt;where &lt;/span&gt;method.Name == methodName
                      &lt;span style="color:blue;"&gt;let &lt;/span&gt;parameters = method.GetParameters()
                      &lt;span style="color:blue;"&gt;where &lt;/span&gt;parameters.Length == args.Length
                            &amp;amp;&amp;amp; parameters.Where((p, i) =&amp;gt; p.ParameterType.IsAssignableFrom(args[i].GetType())).Count() == args.Length
                      &lt;span style="color:blue;"&gt;select new &lt;/span&gt;{ Method = method, Parameters = parameters }).SingleOrDefault();

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(result == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        {
            &lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringBuilder&lt;/span&gt;();
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;Failed to bind method call: &amp;quot;&lt;/span&gt;);
            sb.Append(@this.GetType());
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
            sb.Append(methodName);
            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

            &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = args.Length;
            &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
                sb.Append(args[i].GetType().ToString() + (i != n - 1 ? &lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot; &lt;/span&gt;: &lt;span style="color:#a31515;"&gt;&amp;quot;&amp;quot;&lt;/span&gt;));

            sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;).&amp;quot;&lt;/span&gt;);
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(sb.ToString());
        }

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;result.Method.Invoke(@this, args);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;This needs some explanation I assume. The signature should be straightforward: given an object &lt;em&gt;@this&lt;/em&gt;, we want to call method &lt;em&gt;methodName&lt;/em&gt; with zero or more arguments &lt;em&gt;args&lt;/em&gt;. The result of this will be an &lt;em&gt;object&lt;/em&gt; again (notice we don’t support void return types for methods being called, which isn’t too big of deal when considering &lt;em&gt;functions&lt;/em&gt; as lambdas – i.e. no statement lambdas). What’s more interesting though is the way we find a suitable method. I chose to write it as a gigantic LINQ expression just to show how powerful LINQ can be. Let me walk you through it:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;result = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;method &lt;span style="color:blue;"&gt;in &lt;/span&gt;@this.GetType().GetMethods()
              &lt;span style="color:blue;"&gt;where &lt;/span&gt;method.Name == methodName
              &lt;span style="color:blue;"&gt;let &lt;/span&gt;parameters = method.GetParameters()&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;For all methods available on the left-hand side of the call (i.e. &lt;em&gt;@this&lt;/em&gt;) select those methods that have the same name (case sensitive compare – this would be a binder that mimics C# name resolution for method calls) and let &lt;em&gt;parameters&lt;/em&gt; be a variable containing the parameters for each of the selected methods going forward. In other words, in what follows we’re seeing a sequence of &lt;em&gt;(method, parameters)&lt;/em&gt; pairs mapping each suitable (at least concerning the name) method on the parameters it takes. Next we need to do overload resolution:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;              where &lt;/span&gt;parameters.Length == args.Length&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we make sure the number of arguments on the candidate method matches the number of arguments passed in to the binder’s Call call. This implies we don’t consider things like optional arguments supported by some languages which would mean that having less matching parameters (but not more!) would keep the method as a candidate, although there would need to be some ordering to make sure that methods with more arguments take precedence over methods with arguments supplied through optional values. Notice this simple check makes it also impossible to call a “params” method without stiffing the argument in an array upfront.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;                    &amp;amp;&amp;amp; parameters.Where((p, i) =&amp;gt; p.ParameterType.IsAssignableFrom(args[i].GetType())).Count() == args.Length&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we’re in the clause that’s maybe the most interesting. Here we’re taking all the parameters of the candidate and check that the parameter &lt;em&gt;p &lt;/em&gt;on position &lt;em&gt;i&lt;/em&gt; has a type that’s assignable from the type of the argument passed in to the binder’s Call method. In essence this is &lt;em&gt;contravariance&lt;/em&gt; for arguments. Assume we’re examining a candidate method like this:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;class ExperimentalZoo 
    &lt;br /&gt;{ 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Animal CloneBeast(Mammal g); 

    &lt;br /&gt;}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and we’re calling the binder as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;DynamicBinder.Call(new ExperimentalZoo(), “CloneBeast”, new Giraffe())&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As we’re calling the binder with an argument of type Giraffe (args[0].GetType()) and Giraffe inherits from Mammal (parameters[i].ParameterType), the candidate is compatible. However, if we’d call the method with an argument of type Goldfish it would clearly not be compatible (as a fish is not a mammal). This is precisely what the Where clause above enforces. The Count() == args.Length trick at the end makes sure all of the arguments pass the test (using the All operator would be ideal but it hasn’t an overload passing in the index; alternatively a Zip operator would be beneficial too).&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Finally we have the select clause:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;              select new &lt;/span&gt;{ Method = method, Parameters = parameters }).SingleOrDefault();&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;which simply extracts the method (of type MethodInfo) and the parameters (of type ParameterInfo[]) and makes sure we only found one match. This is another simplification for illustrative purposes only – to be fully compliant with e.g. the C# language, we’d have to implement all of the overload resolution rules including “betterness rules” that select the most optimal overload. More information on this can be found in the C# specification, in v3.0 under “7.4.3 Overload Resolution”. The key takeaway though is that we can tweak this binder as much as we want (e.g., left as an exercise, we could implement resolution that takes extension methods into account) without affecting the generated IL code that will simply call into the binder’s Call method.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;If we find one result, we can just go ahead and call it by calling through the retrieved Method using the Invoke method, passing in the &lt;em&gt;@this&lt;/em&gt; pointer and the &lt;em&gt;args&lt;/em&gt; array.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Connecting the pieces&lt;/h1&gt;

&lt;p&gt;Now that we have our beloved binder, we need to glue it together with our dynamic expression compilation. In concrete terms this means we need to emit a call to DynamicBinder.Call in the generated IL for the DynamicCallExpression. This isn’t too hard either:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(Object == &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldnull);
    &lt;span style="color:blue;"&gt;else
        &lt;/span&gt;Object.Compile(ilgen, ldArgs);

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldstr, Method);

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldc_I4, Arguments.Count);
    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Newarr, &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;LocalBuilder &lt;/span&gt;arr = ilgen.DeclareLocal(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;[]));
    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Stloc, arr);

    &lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0;
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;arg &lt;span style="color:blue;"&gt;in &lt;/span&gt;Arguments)
    {
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldloc, arr);
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldc_I4, i++);
        arg.Compile(ilgen, ldArgs);
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Stelem_Ref);
    }

    ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldloc, arr);

    ilgen.EmitCall(&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;DynamicBinder&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Call&amp;quot;&lt;/span&gt;), &lt;span style="color:blue;"&gt;null&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 going on here? First, we check whether an Object has been specified. This is more of an extensibility point in case our binder would like to implement &lt;em&gt;global functions&lt;/em&gt; (also left as an exercise, for example you could recognize null.Add(1, 2) as a global Add call, translating into Math.Add(…); or, the Method property could be set to “Math.Add” to denote a static method call). We’ll assume the else case holds true for our samples, causing us to call Compile recursively on the Object dynamic expression. This will add the value corresponding to the Object expression tree’s evaluation on top of the stack (note: you can smell call-by-value semantics already, don’t you?). Next, we load the string specified in the Method property onto the stack as well. Currently the stack looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(string) Method 
    &lt;br /&gt;(object) Object.Compile result&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we get into interesting stuff as our binder’s Call method expects to see an object[] as its third parameter. How many arguments? On for each of the DynamicExpression objects in the Arguments collection, so we do &lt;em&gt;Newarr&lt;/em&gt; passing in the object type &lt;em&gt;object&lt;/em&gt; after pushing the number of elements to be allocated on the stack using &lt;em&gt;Ldc_I4&lt;/em&gt; passing in Arguments.Count. Now we have our array, we can store it in a local variable we call “arr”. Time to fill the array by first loading the local, then pushing the index followed by a push of the argument’s value – again obtained by a recursive Compile call on the argument “arg” – and finally calling &lt;em&gt;stelem_ref&lt;/em&gt; (as we’re dealing with System.Object we need _ref). The loop invariant is that it doesn’t change the stack height: it cleanly loads three “arguments” to stelem_ref which brings the stack delta back to 0).&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Ultimately, we load the array local variable and the stack looks like (semantically):&lt;/p&gt;

&lt;blockquote&gt;(object[]) Arguments.Select(arg =&amp;gt; arg.Compile()).ToArray() 
  &lt;br /&gt;(string) Method 

  &lt;br /&gt;(object) Object.Compile()&lt;/blockquote&gt;

&lt;p&gt;ready for a call to DynamicBinder.Call which turns the stack into:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(object) DynamicBinder.Call(Object.Compile(), Method, Arguments.Select(arg =&amp;gt; arg.Compile()).ToArray())&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Again, we have managed to keep the house clean with regards to the stack behavior, i.e. the element on top of the stack contains the value corresponding to the entire (MethodCall)DynamicExpression.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Testing it&lt;/h1&gt;

&lt;p&gt;Does it work? Let’s try with our running sample:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;o = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;call = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Call(o, &lt;span style="color:#a31515;"&gt;&amp;quot;Substring&amp;quot;&lt;/span&gt;, a, b);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;func = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(call, o, a, b);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2));&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Recognize the patterns in the output IL?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="602" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb.png" width="914" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A quick walk-through:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;IL_0000 loads MethodCallDynamicExpression.Object which in turn was compiled into a ldarg V_0 by the ParameterDynamicExpression’s Compile method (this corresponds to “o”) &lt;/li&gt;

  &lt;li&gt;IL_0006 loads MethodCallDynamicExpression.Method &lt;/li&gt;

  &lt;li&gt;IL_000b to IL_0015 prepares the array for the method call arguments to be passed to the binder &lt;/li&gt;

  &lt;li&gt;IL_0016 to IL_0022 puts the first argument (corresponding to “a” translated into ldarg V_1 through ParameterDynamicExpression.Compile) in the array &lt;/li&gt;

  &lt;li&gt;IL_0023 to IL_002f does the same for the second argument (corresponding to “b” translated into ldarg V_2 through ParameterDynamicExpression.Compile) &lt;/li&gt;

  &lt;li&gt;IL_0030 to IL_0036 finally makes the call through the binder, passing in the results of the above and returning the value produced by the binder &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we now set a breakpoint in the DynamicBinder.Call method and let execution continue, we’ll see:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_3.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="361" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb_3.png" width="864" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The third line in the Call Stack is where DynamicInvoke is happening:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.Compile().&lt;strong&gt;&lt;u&gt;DynamicInvoke&lt;/u&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2)&lt;/strong&gt;);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;and through the “External Code” corresponding to our emitted dynamic method we got back into the DynamicBinder that now will pick the right Substring method given lhs “Bart” and arguments 1 and 2. Ultimately the following prints to the screen:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_4.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="64" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb_4.png" width="271" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Magic. To show it’s really extensible we can start to compose things endlessly with our two main ingredients: parameter and method call expressions. Here’s a sample (reverse engineering the nested DynamicExpression factory calls is left as an exercise):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_5.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="71" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_167A/image_thumb_5.png" width="824" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Also left as an exercise to the reader is to find values for o and a through h that produce the displayed output above :-). For the record, here’s the corresponding IL:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;IL_0000: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_0 
    &lt;br /&gt;IL_0004: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0005: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0006: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;Replace&amp;quot; 

    &lt;br /&gt;IL_000b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_0010: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_0015: stloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0016: ldloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0017: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_001c: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_3 

    &lt;br /&gt;IL_0020: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0021: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0022: stelem.ref 

    &lt;br /&gt;IL_0023: ldloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0024: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_0029: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_4 

    &lt;br /&gt;IL_002d: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_002e: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_002f: stelem.ref 

    &lt;br /&gt;IL_0030: ldloc.0&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0031: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_0036: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;Substring&amp;quot; 

    &lt;br /&gt;IL_003b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_0040: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_0045: stloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0046: ldloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0047: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_004c: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_1 

    &lt;br /&gt;IL_0050: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0051: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0052: stelem.ref 

    &lt;br /&gt;IL_0053: ldloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0054: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_0059: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_2 

    &lt;br /&gt;IL_005d: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_005e: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_005f: stelem.ref 

    &lt;br /&gt;IL_0060: ldloc.1&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0061: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_0066: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;Replace&amp;quot; 

    &lt;br /&gt;IL_006b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_0070: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_0075: stloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0076: ldloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0077: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_007c: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_5 

    &lt;br /&gt;IL_0080: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0081: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0082: stelem.ref 

    &lt;br /&gt;IL_0083: ldloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0084: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_0089: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_6 

    &lt;br /&gt;IL_008d: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_008e: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_008f: stelem.ref 

    &lt;br /&gt;IL_0090: ldloc.2&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_0091: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_0096: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;PadRight&amp;quot; 

    &lt;br /&gt;IL_009b: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 2 

    &lt;br /&gt;IL_00a0: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_00a5: stloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00a6: ldloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00a7: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_00ac: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_7 

    &lt;br /&gt;IL_00b0: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00b1: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00b2: stelem.ref 

    &lt;br /&gt;IL_00b3: ldloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00b4: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 1 

    &lt;br /&gt;IL_00b9: ldarg&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; V_8 

    &lt;br /&gt;IL_00bd: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00be: nop&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00bf: stelem.ref 

    &lt;br /&gt;IL_00c0: ldloc.3&amp;#160;&amp;#160;&amp;#160; &lt;br /&gt;IL_00c1: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_00c6: ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &amp;quot;ToUpper&amp;quot; 

    &lt;br /&gt;IL_00cb: ldc.i4&amp;#160;&amp;#160;&amp;#160;&amp;#160; 0 

    &lt;br /&gt;IL_00d0: newarr&amp;#160;&amp;#160;&amp;#160;&amp;#160; Object 

    &lt;br /&gt;IL_00d5: stloc.s&amp;#160;&amp;#160;&amp;#160; V_4 

    &lt;br /&gt;IL_00d7: ldloc.s&amp;#160;&amp;#160;&amp;#160; V_4 

    &lt;br /&gt;IL_00d9: call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; System.Object Call(System.Object, System.String, System.Object[])/BinderFun.DynamicBinder 

    &lt;br /&gt;IL_00de: ret&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Enjoy! Next time … who knows what?&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=13925" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 2</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/27/to-bind-or-not-to-bind-dynamic-expression-trees-part-2.aspx</link><pubDate>Wed, 27 Aug 2008 23:05:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13917</guid><dc:creator>bart</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13917</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/27/to-bind-or-not-to-bind-dynamic-expression-trees-part-2.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;Welcome back to the dynamic expression tree fun. Last time we designed our simplified expression tree class library we’ll be using to enable dynamic treatment of objects. Today, we’ll take this one step further by emitting IL code that resolves the operations invoked on such dynamic objects &lt;u&gt;at runtime&lt;/u&gt; through a mechanism called binders. Before we dive in, let me point out that everything discussed in this series is greatly simplified just to illustrate the core ideas and base mechanisms/principles that make dynamic language stuff work.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Introducing IL generation&lt;/h1&gt;  &lt;p&gt;Dynamic code compilation is a wonderful thing. It’s not that hard once you get the basics right (and have some level of IL opcode understanding) but quite hard to debug. Luckily we have tools like &lt;a href="http://blogs.msdn.com/haibo_luo/archive/2008/03/07/8107924.aspx"&gt;Haibo Luo’s IL Visualizer&lt;/a&gt;. Since I’ll be using this, download it, extract the ZIP file, compile the whole solution and copy ILMonitor\bin\Debug\*.dll to %programfiles%\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers. Alternatively you can put it in your personal Visual Studio 2008\Visualizers folder.&lt;/p&gt;  &lt;p&gt;So, what’s our task? Assume we have the following piece of sample code:&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;Program
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;o = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;call = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Call(o, &lt;span style="color:#a31515;"&gt;&amp;quot;Substring&amp;quot;&lt;/span&gt;, a, b);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;func = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(call, o, a, b);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.&lt;strong&gt;&lt;u&gt;Compile()&lt;/u&gt;&lt;/strong&gt;.DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2));
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;We already know how to construct the objects and to represent it as a string (which would be (o, a, b) =&amp;gt; o.Substring(a, b)). Now we need to focus on the marked Compile method on LambdaDynamicExpression. Starting with the signature of the delegate, we want to create (at runtime) a method that takes in three “dynamic” parameters (corresponding to parameter expressions o, a and b), returning a resulting object. Since we don’t have any type information available, everything should be System.Object, so we’d end up with the following delegate:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#0000ff"&gt;delegate object &lt;/font&gt;&lt;font color="#008080"&gt;TheDynamicLambdaFunction&lt;/font&gt;(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o, &lt;font color="#0000ff"&gt;object &lt;/font&gt;a, &lt;font color="#0000ff"&gt;object &lt;/font&gt;b);&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Looking at Compile as a black box, it will return an instance of this delegate pointing at an on-the-fly generated method corresponding to the lambda’s body expression. Returning a System.Delegate, one can call DynamicInvoke (or cast it to a compatible delegate) to invoke it with the given parameters. Obviously we want the call to do “the right thing”, in the sample above it would correspond to a method call to System.String::Substring on “Bart”, passing in startIndex 1 and length 2, producing another string containing “ar”.&lt;/p&gt;

&lt;p&gt;It should be clear that we need to emit IL on the fly to translate the lambda expression but also the lambda’s body which could be anything, not just a MethodCallDynamicExpression. Since we lack other expression node types, one such (trivial) thing would be:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(&lt;strong&gt;&lt;u&gt;x&lt;/u&gt;&lt;/strong&gt;, x);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;which is just the identity function (the underlined bold ‘o’ above indicates the lamdba’s body). I intentionally named the expression above “I” conform SKI combinators where I is defined as λx . x. Similarly we could define the K combinator as:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;y = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;K = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(x, x, y);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(K);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(K.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 123));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;but we got sidetracked, so time to move on. The whole point here is that we can’t assume the body of the lambda to be a MethodCallDynamicExpression. So, how do we tackle this? An important observation one can make is this: an expression represents a single value. Right, so what? Wait a minute, is IL-code not stack-based? Adding the two things together we could think of the following solution:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Calling a Compile method on an expression tree object, given a writeable stream for IL instructions, should add all the instructions to the stream required to evaluate the expression, leaving the result of the evaluation on top of the stack.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A LambdaDynamicExpression is the only dynamic expression that supports a publicly visible Compile method. It’s pseudo-code would look like:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Create an IL stream; here the IL stack is empty.&lt;/li&gt;

  &lt;li&gt;Take the Body expression and compile it by emitting IL instructions for it; this causes the IL stack to be one high.&lt;/li&gt;

  &lt;li&gt;Add an IL return instruction to return the object on top of the stack.&lt;/li&gt;

  &lt;li&gt;Return a delegate pointing to the method represented by the generated IL code.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Supporting expression compilation&lt;/h1&gt;

&lt;p&gt;To make this work, we’ll first extend the base class by adding one more method:&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;Class representing a dynamic expression tree.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Appends IL instructions to calculate the expression&amp;#39;s runtime value, putting it on top of the evaluation stack.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;ilgen&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;IL generator to append to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;ldArgs&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Lambda argument mappings.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;protected internal abstract void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs);&lt;/pre&gt;

  &lt;pre class="code"&gt;    …&lt;br /&gt;}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This method will take in two things: the IL generator (referred to as “IL stream” in the previous paragraph) and a mapping table for the lambda’s parameter expressions. Why do we need the latter, or better: what does it map the parameter expressions to? Assume we’re compiling&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(o, a, b) =&amp;gt; o.Substring(a, b)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;While traversing the expression tree, asking every node in the correct order to emit IL instructions, we’ll encounter references to the parameters again. Our goal is to write a dynamic method looking like this:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#0000ff"&gt;object &lt;/font&gt;GeneratedDynamicMethod(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o, &lt;font color="#0000ff"&gt;object &lt;/font&gt;a, &lt;font color="#0000ff"&gt;object &lt;/font&gt;b)

    &lt;br /&gt;{

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;o.Substring(a, b);

    &lt;br /&gt;}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;where the . obviously denotes a dynamic method call in this case. As we encounter parameter expressions like o, a or b during the translation for the method body, we need to know how to load those parameters from the argument list on the dynamic method. First of all, notice the lambda parameters got mapped in order of specification to correspond to arguments on the generated dynamic method, i.e. o as the first lambda parameter and is the first parameter on the generated method. And so on. This is precisely what the ldArgs argument on Compile stands for: a mapping from the parameter expression representation from the lambda parameters onto the concrete indices for the arguments:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;o –&amp;gt; 0
    &lt;br /&gt;a –&amp;gt; 1

    &lt;br /&gt;b –&amp;gt; 2&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Whenever we encounter such a parameter expression during the compilation, we know the position of the argument, so we can emit a &lt;em&gt;ldarg&lt;/em&gt; instruction. This is the most trivial Compile override:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!ldArgs.ContainsKey(&lt;span style="color:blue;"&gt;this&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;Parameter expression &amp;quot; &lt;/span&gt;+ Name + &lt;span style="color:#a31515;"&gt;&amp;quot; is not in scope.&amp;quot;&lt;/span&gt;);

        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg, ldArgs[&lt;span style="color:blue;"&gt;this&lt;/span&gt;]);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    …
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This simply says, whenever code needs to be emitted for a ParameterDynamicExpression, simply try to find it in the dictionary to map it onto the formal parameter index on the dynamic method being emitted and turn it into a &lt;em&gt;ldarg &lt;/em&gt;instruction for that argument index. Real full-fledged expression tree implementations would be slightly more complicated because arguments could be hidden when dealing with nested lambdas (quoting, invocation expressions, etc) but that would take us too far away from home.&lt;/p&gt;

&lt;p&gt;For the LambdaDynamicExpression, besides a public Compile method, there will also be an override to the inherited one. It simply asks the Body expression to emit itself (which will result in a one-level high stack containing the evaluation result of the body expression), followed by a ret instruction (simply returning the value evaluated through the Body’s IL code preceding it):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
    {
        Body.Compile(ilgen, ldArgs);
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ret);
    }&lt;/pre&gt;

&lt;pre class="code"&gt;    …&lt;br /&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Emitting code&lt;/h1&gt;

&lt;p&gt;For this post, we’ll omit an implementation for MethodCallDynamicExpression as that will be part of the next post focusing on binders. All we want to get to work today is the I combinator or identity function (yeah, another world-beater :-)):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(x, x);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&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;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;In other words, today we’ll focus on the plumbing of emitting the code and wrapping the method in a delegate that can be returned upon calling LambdaDynamicExpression.Compile. The result for the sample above would be equivalent to:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
{
    &lt;span style="color:blue;"&gt;return new &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;(&lt;u&gt;&lt;span style="color:blue;"&gt;delegate&lt;/span&gt;(&lt;span style="color:blue;"&gt;object &lt;/span&gt;x) { &lt;span style="color:blue;"&gt;return &lt;/span&gt;x; }&lt;/u&gt;);
}&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;The underlined portion is the code corresponding to I’s compilation. In IL-terms it would be as simplistic as this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;ldarg.0
    &lt;br /&gt;ret&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This emitted IL method body then needs to get the signature that says “taking in an object, returning an object”. All of this makes up the &lt;em&gt;dynamic method&lt;/em&gt;. But we’re not done yet, as we need to return a delegate to it. In the free translation above, I’ve leveraged the generic System.Func&amp;lt;T1,R&amp;gt; delegate but we only have a limited number of those (up to four arguments), so what if we encounter a method that takes more arguments? Indeed, we’ll need to generate our own delegate types as well. Notice we could cache those very efficiently: the ones with arity (~ number of parameters) up to 4 could simply be mapped onto System.Func delegates with System.Object type parameters, while others would be generated on the fly and kept for reuse if another method with same arity gets compiled. We’ll omit this optimization for now.&lt;/p&gt;

&lt;p&gt;Here’s how the code to create our own delegate type looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;GetDynamicDelegate(&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] argumentTypes, &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;returnType)
{
    &lt;span style="color:green;"&gt;//
    // Assemblies contain modules; generate those with unique names.
    // The generated assembly is runtime only (doesn&amp;#39;t need to be saved to disk).
    //
    &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:#2b91af;"&gt;Guid&lt;/span&gt;.NewGuid().ToString()), &lt;span style="color:#2b91af;"&gt;AssemblyBuilderAccess&lt;/span&gt;.Run);
    &lt;span style="color:#2b91af;"&gt;ModuleBuilder &lt;/span&gt;moduleBuilder = assemblyBuilder.DefineDynamicModule(&lt;span style="color:#2b91af;"&gt;Guid&lt;/span&gt;.NewGuid().ToString());

    &lt;span style="color:green;"&gt;//
    // Our delegate is a private sealed type deriving from MultiCastDelegate.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder = moduleBuilder.DefineType(&lt;span style="color:#a31515;"&gt;&amp;quot;Lambdas&amp;quot;&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.NotPublic | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.Sealed | &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:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MulticastDelegate&lt;/span&gt;));

    &lt;span style="color:green;"&gt;//
    // The delegate&amp;#39;s constructor is a &amp;quot;special name&amp;quot; method with signature (object native int).
    // It doesn&amp;#39;t have a method body by itself; rather, it&amp;#39;s supplied by the managed runtime.
    //
    &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:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;IntPtr&lt;/span&gt;) });
    ctorBuilder.SetImplementationFlags(&lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Runtime | &lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Managed);

    &lt;span style="color:green;"&gt;//
    // We only need the Invoke method (BeginInvoke and EndInvoke are irrelevant for us).
    // It doesn&amp;#39;t have a method body by itself; rather, it&amp;#39;s supplied by the managed runtime.
    // Here our delegate signature is enforced.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodBuilder &lt;/span&gt;invokeMethodBuilder = typeBuilder.DefineMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Invoke&amp;quot;&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.NewSlot | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.HideBySig | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Virtual, &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.HasThis, returnType, argumentTypes);
    invokeMethodBuilder.SetImplementationFlags(&lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Runtime | &lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Managed);

    &lt;span style="color:green;"&gt;//
    // Return the created delegate type.
    // Notice we could cache this for reuse by other dynamic methods.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;typeBuilder.CreateType();
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Lots of attribute flags which you can read all about in the CLI specification. I don’t pretend to memorize all of those attributes; why would I if ILDASM makes life just great? :-)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="260" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb.png" width="631" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the screenshot of ILDASM showing a delegate for a method with signature object(object, object) as you can see on the Invoke method. We don’t need any of the asynchronous pattern implementation, so we just need a constructor and Invoke method (see section IIA.13.6 on “Delegates” in the CLI standard). One special thing about those is they don’t have an IL code body as they are “runtime managed” (see IIA.14.4.3 on “Implementation Attributes of Methods” in the CLI standard):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_3.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="166" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_3.png" width="640" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that we can generate the delegate, we just need to ask the lambda (since that’s the root) expression tree to emit its IL code, which will traverse the entire tree. In order to be able to do this, we need to keep mapping information about the lambda parameters mapped onto the formal arguments as mentioned earlier. Here’s the result:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
{
    &lt;span style="color:green;"&gt;//
    // Map the lambda parameters onto formal argument indices.
    // Also build up the argument type array.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;args = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[Parameters.Count];
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;ldArgs = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;();
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; args.Length; i++)
    {
        args[i] = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;);
        ldArgs[Parameters[i]] = i;
    }

    &lt;span style="color:green;"&gt;//
    // Compile the expression tree to an IL method body.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;method = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicMethod&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;), args);
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;ilgen = method.GetILGenerator();
    Compile(ilgen, ldArgs);

    &lt;span style="color:green;"&gt;//
    // Get the delegate matching the dynamic method signature.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;dynamicDelegate = GetDynamicDelegate(args, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;));

    &lt;span style="color:green;"&gt;//
    // Return a delegate pointing at our dynamic method.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;method.CreateDelegate(dynamicDelegate);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This code should be relatively straightforward. First we create the mapping while building up an array just containing typeof(object)’s (since all arguments are objects in our dynamic world). Next we create a dynamic method with the right signature, produce the IL generator and let the expression compilation do all of the work to emit the IL. And finally we stick the whole thing in a dynamically created delegate that matches the signature, returning that to the caller. Setting a breakpoint on the last line and executing for the “I” identity combinator shows this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_4.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="184" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_4.png" width="560" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the IL visualizer we installed earlier. Notice the friendly string representation for the dynamic method shows the signature, which matches the one of the dynamic lambda in the watch window (which is just “I”). Bringing up the IL visualizer shows stunningly complex code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_5.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="133" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_5.png" width="305" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ignore the NOPs inserted by the IL generator, but IL_0000 was emitted by ParameterDynamicExpression.Compile through the compilation of the lambda body. IL_0006 was emitted subsequently by LambdaDynamicExpression.Compile and the stack is nicely in balance. Sure enough, the result printed is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_6.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="119" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_6.png" width="372" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Woohoo – truly dynamic (though simplistic) execution! Next time: method call expressions and binders.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=13917" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 1</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-1.aspx</link><pubDate>Wed, 27 Aug 2008 05:40:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13913</guid><dc:creator>bart</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13913</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-1.aspx#comments</comments><description>&lt;p&gt;In the previous post, I outlined the use of the expression trees from the System.Linq.Expressions namespace. Let’s recap to set the scene:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt; data = (&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt; &lt;/font&gt;s, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt; &lt;/font&gt;a, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt; &lt;/font&gt;b) =&amp;gt; s.Substring(a, b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;produces (deep breadth)&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“s”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“a”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“b”&lt;/font&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt; data = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt;(       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)&lt;/u&gt;.GetMethod(&lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, &lt;u&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Type&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;), &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;) }&lt;/u&gt;), a, b),         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b         &lt;br /&gt;);         &lt;br /&gt;        &lt;br /&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt; fun = data.Compile();         &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where I’ve indicated all the strong typing using underlines. Wow, that’s a lot dude! Based on all of this strong typing, there are little or no runtime surprises possible concerning running the right method (unless a MissingMethodException occurs for some reason). Obviously, expression trees could be much more complex but to illustrate the core points of the type system, we’ll restrict ourselves to parameters, method calls and lambdas.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;So what do we want to try now? We want to design an API similar to the one used above but without all this type information. Essentially, it would look like:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“s”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“a”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“b”&lt;/font&gt;);     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008080"&gt;LambdaExpression&lt;/font&gt; data = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, a, b),       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b       &lt;br /&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Delegate&lt;/font&gt; fun = data.Compile();       &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun.&lt;u&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;Invoke&lt;/u&gt;(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;and all of a sudden we see the dynamic aspect lurking around the corner on the very last line where we call through the weakly-typed delegate passing in three &lt;em&gt;objects&lt;/em&gt; which just happen to be a string and two ints, causing the lookup for a Substring method applied to s (becoming “Bart”) with arguments a and b (respectively 1 and 2) to succeed. The important thing here though is that a “Substring” method with a compatible signature might be available on another type, maybe type Bar, but taking in two longs:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Foo &lt;/font&gt;Substring(&lt;font color="#0000ff"&gt;long &lt;/font&gt;a, &lt;font color="#0000ff"&gt;long &lt;/font&gt;b) { … }       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The calling code would still work and the console would print the result of Foo.ToString on the instance returned by Bar.Substring. What it takes to make this work consists of three things:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Dynamic expression trees (i.e. as the one above with stripped type information); &lt;/li&gt;    &lt;li&gt;IL code generation at runtime on the fly (to produce the delegate “fun” in the sample above) &lt;/li&gt;    &lt;li&gt;Binders (things that provide runtime support to resolve method calls) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Of course you could go much further than this with complete ASTs (the big brothers to expression trees) and “rules” but we’re not going to reinvent the DLR :-). &lt;a href="http://blogs.msdn.com/mmaly"&gt;Martin Maly&lt;/a&gt; has quite some information on those topics on his blog (must-reads!). Today we’ll cover the first bullet point.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Our dynamic expression trees&lt;/h1&gt;  &lt;p&gt;To disambiguate with the LINQ expression trees, let’s sneak the word Dynamic in, making our sample look like:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“s”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“a”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“b”&lt;/font&gt;);     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008080"&gt;LambdaDynamicExpression&lt;/font&gt; data = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Lambda(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, a, b),       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b       &lt;br /&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Delegate&lt;/font&gt; fun = data.Compile();       &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun.&lt;u&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;Invoke&lt;/u&gt;(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;All of those *DynamicExpression classes extend the DynamicExpression base class while having a factory method on DynamicExpression too, following the design of LINQ’s expression trees. We’ll omit the NodeType property for simplicity and the Type property, because we obviously don’t want a static type to be associated with each expression tree node. We’ll also get rid of a lot of node types, just leaving the factories in for our three node types:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_E57/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="369" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_E57/image_thumb.png" width="595" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So, how does this look like? The factory methods will be just convenient syntax around internal constructor calls producing the concrete node types. In addition, we’ll override ToString to produce a friendly-on-the-eye string representation of expression trees, much like our static LINQ friends. First, the DynamicExpression base class:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;Parameter(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;(name);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression &lt;/span&gt;Call(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;instance, &lt;span style="color:blue;"&gt;string &lt;/span&gt;method, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;[] arguments)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression&lt;/span&gt;(instance, method, arguments);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;Lambda(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;body, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;[] parameters)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression&lt;/span&gt;(body, parameters);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;    &lt;/font&gt;protected internal abstract void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb);

&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;    public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringBuilder&lt;/span&gt;();
        ToString(sb);
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;sb.ToString();
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;We’ll extend this class a bit more in the next part where we’ll tackle compilation, but let’s move on to each of the three subtypes right now:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;ParameterDynamicExpression(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        Name = name;
    }

    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Name { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

&lt;span style="color:blue;"&gt;    protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        sb.Append(Name);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Nothing surprising here. The expression for a dynamic method call is a slightly bit more complicated :-)…&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;MethodCallDynamicExpression(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;instance, &lt;span style="color:blue;"&gt;string &lt;/span&gt;method, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;[] arguments)
    {
        Object = instance;
        Method = method;
        Arguments = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt;(arguments);
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt; Arguments { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Object { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Method { &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;pre class="code"&gt;    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        Object.ToString(sb);
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
        sb.Append(Method);
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = Arguments.Count;
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
        {
            Arguments[i].ToString(sb);
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != n - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }

        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;)&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;I told’ya it was going to be mind-blowing. The core thing to notice though is the composability because of the use of DynamicExpressions as the Object (i.e. the instance where we’ll invoke the method on) and the Arguments collection members. Also notice we don’t support static method calls in here (for which Object would be null – you can envision the right checking in the factory method, omitted for brevity) although it would be perfectly possible to come up with such a thing (think about “global functions” for example, but remember we don’t have a type that tells us where to look for the method – ideally you’d have a mixture of statically and dynamically typed trees interwoven). Oh, and the pretty printing logic in ToString isn’t too complex either…&lt;/p&gt;

&lt;p&gt;Finally, let’s move on to the lambda expression class:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;LambdaDynamicExpression(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;body, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;[] parameters)
    {
        Body = body;
        Parameters = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;&amp;gt;(parameters);
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Body { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;&amp;gt; Parameters { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
    {
        &lt;span style="color:blue;"&gt;return null&lt;/span&gt;;
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = Parameters.Count;
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
        {
            Parameters[i].ToString(sb);
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != n - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }

        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;) =&amp;gt; &amp;quot;&lt;/span&gt;);
        Body.ToString(sb);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Same deal concerning parameterization based on DynamicExpression instances. I promise you the Compile method will be pretty interesting to say the least, so stay tuned for the next post!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=13913" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item></channel></rss>