<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blog.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 : C# 4.0</title><link>http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx</link><description>Tags: C# 4.0</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Reader Challenge – Fault Handlers in C#</title><link>http://blog.bartdesmet.net/blogs/bart/archive/2009/12/06/reader-challenge-fault-handlers-in-c.aspx</link><pubDate>Sun, 06 Dec 2009 20:57:48 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14892</guid><dc:creator>bart</dc:creator><slash:comments>24</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14892</wfw:commentRss><comments>http://blog.bartdesmet.net/blogs/bart/archive/2009/12/06/reader-challenge-fault-handlers-in-c.aspx#comments</comments><description>&lt;p&gt;The CLR’s exception handling facilities provide for &lt;em&gt;protected blocks&lt;/em&gt; (“try”) one can associate a &lt;em&gt;handler&lt;/em&gt; with. There are four kinds of handlers, and exactly one can be associated with a protected block (but nesting can be used to associate multiple handlers with a block of code):&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;A &lt;strong&gt;finally handler &lt;/strong&gt;is executed whenever the block is exited, regardless of whether this happened by normal control flow or an unhandled exception. C# exposes this using the finally keyword.&lt;/li&gt;    &lt;li&gt;A &lt;strong&gt;type-filtered handler&lt;/strong&gt; handles an exception of a specified class or any of its subclasses. Better known as a “catch block”, C# provides this through its catch keyword.&lt;/li&gt;    &lt;li&gt;A &lt;strong&gt;user-filtered handler&lt;/strong&gt; runs user-specified code to determine whether the exception should be ignored, handled by the associated handler, or passed on to the next protected block. C# doesn’t expose this, but Visual Basic does by means of its When keyword.&lt;/li&gt;    &lt;li&gt;A &lt;strong&gt;fault handler &lt;/strong&gt;is executed if an exception occurs, but not on completion of normal control flow. Neither C# nor Visual Basic provide a fault handler language feature.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In this reader challenge, we’re going to focus on fault handlers. Due to their lack of language surface, their effect is often mimicked by using some local state to determine whether the protected block exited gracefully or not:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;bool &lt;/font&gt;success = &lt;font color="#0000ff"&gt;false&lt;/font&gt;;        &lt;br /&gt;&lt;font color="#0000ff"&gt;try&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; // Do stuff         &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; success = &lt;font color="#0000ff"&gt;true&lt;/font&gt;;        &lt;br /&gt;}        &lt;br /&gt;&lt;font color="#0000ff"&gt;finally&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(!success)        &lt;br /&gt;&amp;#160;&amp;#160; {        &lt;br /&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // There was a fault. Do something special.&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160; }        &lt;br /&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160; // Fault or not; this is what finally does.&lt;/font&gt;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;If an exception happens during “Do stuff”, we end up in the finally block and come to conclude success was never set to true. This indicates an error happened, and we should handle the fault case. However, this technique can get a bit tricky when there are different paths exiting the try block: one could return from the enclosing method in various places, requiring the “success = true” code to be sprinkled around. This is exactly what exception handling was designed for: reducing clutter in your code that has to do with error condition/code tracking. So, we’re defeating that purpose.&lt;/p&gt;  &lt;p&gt;Today’s challenge is to create a true fault handler in C#, just for the sake of it. This is merely a brain teaser, encouraging readers to find out what happens behind the scenes of compiled C# code. We won’t be addressing certain concerns like non-local return (the case I mentioned above) but will be hunting for the true “fault” handler treasure hidden deeply in the C# compiler’s IL code emitter. The operational specification is the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;f = Fault(() =&amp;gt; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;&amp;quot;Okay&amp;quot;&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;gt; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;&amp;quot;Fault&amp;quot;&lt;/font&gt;));        &lt;br /&gt;f();        &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;g = Fault(() =&amp;gt; { &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;Exception&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;Oops&amp;quot;&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;gt; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;&amp;quot;Fault&amp;quot;&lt;/font&gt;));        &lt;br /&gt;&lt;font color="#0000ff"&gt;try&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; g();        &lt;br /&gt;}        &lt;br /&gt;&lt;font color="#0000ff"&gt;catch &lt;/font&gt;(&lt;font color="#008080"&gt;Exception &lt;/font&gt;ex)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(ex);        &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The above should produce the following output:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;Okay &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;Fault       &lt;br /&gt;System.Exception: Oops        &lt;br /&gt;&amp;#160;&amp;#160; at Program.&amp;lt;Main&amp;gt;b__2()        &lt;br /&gt;&amp;#160;&amp;#160; &lt;em&gt;(I won’t reveal the secrets here yet…)         &lt;br /&gt;&lt;/em&gt;&amp;#160;&amp;#160; at Program.Main()&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Action f illustrates the non-exceptional case where the fault handler is not invoked (a finally handler would get invoked). Action g illustrates the exceptional case where the fault handler gets invoked and the exception bubbles up to the catch-block surrounding its invocation.&lt;/p&gt;  &lt;p&gt;It’s strictly forbidden to use local state in Fault (or a method it calls) to track the successful execution of the protected block. Therefore, the below is an invalid solution:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static&lt;/font&gt; &lt;font color="#008080"&gt;Action &lt;/font&gt;Fault(&lt;font color="#008080"&gt;Action &lt;/font&gt;protectedBlock, &lt;font color="#008080"&gt;Action &lt;/font&gt;faultHandler)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return&lt;/font&gt; () =&amp;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;bool &lt;/font&gt;success = &lt;font color="#0000ff"&gt;false&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;try&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; protectedBlock();        &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; success = &lt;font color="#0000ff"&gt;true&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; &lt;font color="#0000ff"&gt;finally&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;if &lt;/font&gt;(!success)        &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; faultHandler();        &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;Moreover, execution of your Fault method should really use a fault handler as encountered in IL code. It should &lt;strong&gt;be&lt;/strong&gt; a fault handler, &lt;strong&gt;not mimic&lt;/strong&gt; one. In addition, you should not go for a solution where you write a Fault method in ILASM by hand and link it as a netmodule in a C# project, using al.exe:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;.class private &lt;/font&gt;&lt;font color="#008080"&gt;FaultClosure&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.field class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; protectedBlock        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.field class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; faultHandler &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160; &lt;font color="#0000ff"&gt;.method void &lt;/font&gt;.ctor()        &lt;br /&gt;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldarg.0&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;call instance void &lt;/font&gt;[mscorlib]&lt;font color="#008080"&gt;System.Object&lt;/font&gt;::.ctor()        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ret&lt;/font&gt;        &lt;br /&gt;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;&amp;#160; .method void &lt;/font&gt;Do()        &lt;br /&gt;&amp;#160; {        &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; .try&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; &lt;font color="#0000ff"&gt;ldarg.0&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldfld&lt;/font&gt;&amp;#160;&lt;font color="#0000ff"&gt;class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; &lt;font color="#008080"&gt;Program&lt;/font&gt;/&lt;font color="#008080"&gt;FaultClosure&lt;/font&gt;::protectedBlock        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;callvirt instance void &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt;::Invoke()        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;leave.s&lt;/font&gt; END        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;&lt;strong&gt;&lt;u&gt;fault&lt;/u&gt;&lt;/strong&gt;&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; &lt;font color="#0000ff"&gt;ldarg.0&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;ldfld class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; &lt;font color="#008080"&gt;Program&lt;/font&gt;/&lt;font color="#008080"&gt;FaultClosure&lt;/font&gt;::faultHandler        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;callvirt instance void &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt;::Invoke()        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;endfault&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; END: &lt;font color="#0000ff"&gt;ret&lt;/font&gt;        &lt;br /&gt;&amp;#160; }        &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;.method static class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; Fault(&lt;font color="#0000ff"&gt;class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; protectedBlock, &lt;font color="#0000ff"&gt;class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; faultHandler)        &lt;br /&gt;{        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.locals init &lt;/font&gt;(&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Program&lt;/font&gt;/&lt;font color="#008080"&gt;FaultClosure &lt;/font&gt;V_0)        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;newobj void &lt;/font&gt;&lt;font color="#008080"&gt;Program&lt;/font&gt;/&lt;font color="#008080"&gt;FaultClosure&lt;/font&gt;::.ctor()        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;&amp;#160; stloc.0         &lt;br /&gt;&amp;#160; ldloc.0          &lt;br /&gt;&amp;#160; ldarg.0          &lt;br /&gt;&amp;#160; stfld class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action Program&lt;/font&gt;/&lt;font color="#008080"&gt;FaultClosure&lt;/font&gt;::protectedBlock        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;&amp;#160; ldloc.0         &lt;br /&gt;&amp;#160; ldarg.1          &lt;br /&gt;&amp;#160; stfld class &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt; &lt;font color="#008080"&gt;Program&lt;/font&gt;/&lt;font color="#008080"&gt;FaultClosure&lt;/font&gt;::faultHandler        &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160; ldloc.0&lt;/font&gt;        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;ldftn instance void &lt;/font&gt;&lt;font color="#008080"&gt;Program&lt;/font&gt;/&lt;font color="#008080"&gt;FaultClosure&lt;/font&gt;::Do()        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;newobj void &lt;/font&gt;[System.Core]&lt;font color="#008080"&gt;System.Action&lt;/font&gt;::.ctor(&lt;font color="#0000ff"&gt;object&lt;/font&gt;, &lt;font color="#0000ff"&gt;native int&lt;/font&gt;)        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;ret&lt;/font&gt;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Again, this exercise is just for fun with no profit other than brain stimulation. Hint: what C# 2.0 or later feature may cause a “fault” block to be emitted (i.e. if you ildasm a compiled valid C# application, you can find a “fault” keyword)?&lt;/p&gt;  &lt;p&gt;Happy holidays!&lt;/p&gt;&lt;img src="http://blog.bartdesmet.net/aggbug.aspx?PostID=14892" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+2.0/default.aspx">C# 2.0</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx">Crazy Sundays</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><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://blog.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://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14848</wfw:commentRss><comments>http://blog.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://blog.bartdesmet.net/aggbug.aspx?PostID=14848" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blog.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://blog.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://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14709</wfw:commentRss><comments>http://blog.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://blog.bartdesmet.net/aggbug.aspx?PostID=14709" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blog.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://blog.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://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14702</wfw:commentRss><comments>http://blog.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://blog.bartdesmet.net/aggbug.aspx?PostID=14702" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/Functional+programming/default.aspx">Functional programming</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx">Crazy Sundays</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>Statement Trees With Less Pain – Follow-Up on System.Linq.Expressions v4.0</title><link>http://blog.bartdesmet.net/blogs/bart/archive/2009/08/11/statement-trees-with-less-pain-follow-up-on-system-linq-expressions-v4-0.aspx</link><pubDate>Tue, 11 Aug 2009 16:06:22 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14657</guid><dc:creator>bart</dc:creator><slash:comments>13</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14657</wfw:commentRss><comments>http://blog.bartdesmet.net/blogs/bart/archive/2009/08/11/statement-trees-with-less-pain-follow-up-on-system-linq-expressions-v4-0.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;In my last post, &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/10/expression-trees-take-two-introducing-system-linq-expressions-v4-0.aspx?CommentPosted=true#commentmessage"&gt;Expression Trees, Take Two – Introducing System.Linq.Expressions v4.0&lt;/a&gt;, I showed how to the extensions to the LINQ expression trees API opens up for full-blown statement trees including support for assignment, control flow, etc. One popular question that came up in the comments section is on the lack of language-level support for statement trees, like this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;/u&gt;&lt;/strong&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&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;&amp;gt;&lt;strong&gt;&lt;u&gt;&amp;gt;&lt;/u&gt;&lt;/strong&gt; getPrimes = to =&amp;gt;
{
    &lt;span style="color:blue;"&gt;var &lt;/span&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;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;n = 2; n &amp;lt;= to; n++)
    {
        &lt;span style="color:blue;"&gt;bool &lt;/span&gt;found = &lt;span style="color:blue;"&gt;false&lt;/span&gt;;

        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;d = 2; d &amp;lt;= &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Sqrt(n); d++)
        {
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(n % d == 0)
            {
                found = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
                &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
            }
        }

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!found)
            res.Add(n);
    }
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;res;
};&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;At this point, the above won’t work and trigger the following compile error:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;A lambda expression with a statement body cannot be converted to an expression tree&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This hasn’t changed from the previous release. Though it would be a nice feature to have, there are various reasons not to have it integrated with the language at this point. My posts to the comments section of my previous post elaborate on some of the conservative constraints employed during language design, applied to this particular case. So, sorry: not at this point.&lt;/p&gt;

&lt;p&gt;The result is the above turns into quite an involved statement tree declaration if done by hand. Let’s repeat it here to set the scene:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;to = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;to&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&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:#a31515;"&gt;&amp;quot;res&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;n = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;n&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;found = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;bool&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;found&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;d = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;d&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;breakOuter = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Label();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;breakInner = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Label();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;getPrimes = 
    &lt;span style="color:green;"&gt;// Func&amp;lt;int, List&amp;lt;int&amp;gt;&amp;gt; getPrimes =
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&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;&amp;gt;&amp;gt;(
        &lt;span style="color:green;"&gt;// {
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
            &lt;span style="color:green;"&gt;// List&amp;lt;int&amp;gt; res;
            &lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { res },
            &lt;span style="color:green;"&gt;// res = new List&amp;lt;int&amp;gt;();
            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                res,
                &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.New(&lt;span style="color:blue;"&gt;typeof&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;/u&gt;&lt;/strong&gt;
            ),
            &lt;span style="color:green;"&gt;// {
            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                &lt;span style="color:green;"&gt;// int n;
                &lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { n },
                &lt;span style="color:green;"&gt;// n = 2;
                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                    n,
                    &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)&lt;/u&gt;&lt;/strong&gt;
                ),
                &lt;span style="color:green;"&gt;// while (true)
                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Loop(
                    &lt;span style="color:green;"&gt;// {
                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                        &lt;span style="color:green;"&gt;// if
                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                            &lt;span&gt;// (!
&lt;strong&gt;                            &lt;u&gt;Expression&lt;/u&gt;&lt;/strong&gt;&lt;/span&gt;&lt;strong&gt;&lt;u&gt;.Not(&lt;/u&gt;
&lt;/strong&gt;                                &lt;span style="color:green;"&gt;// (n &amp;lt;= to)
&lt;strong&gt;                                &lt;/strong&gt;&lt;/span&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.LessThanOrEqual(&lt;/u&gt;
                                    &lt;u&gt;n,&lt;/u&gt;
                                    &lt;u&gt;to&lt;/u&gt;
                                &lt;u&gt;)&lt;/u&gt;
&lt;/strong&gt;                            &lt;span style="color:green;"&gt;// )
&lt;strong&gt;                            &lt;/strong&gt;&lt;/span&gt;&lt;strong&gt;&lt;u&gt;)&lt;/u&gt;,
&lt;/strong&gt;                            &lt;span style="color:green;"&gt;// break;
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakOuter)
                        ),
                        &lt;span style="color:green;"&gt;// {
                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                            &lt;span style="color:green;"&gt;// bool found;
                            &lt;/span&gt;&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { found },
                            &lt;span style="color:green;"&gt;// found = false;
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                                found,
                                &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue;"&gt;false&lt;/span&gt;)
&lt;/u&gt;&lt;/strong&gt;                            ),
                            &lt;span style="color:green;"&gt;// {
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                &lt;span style="color:green;"&gt;// int d;
                                &lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { d },
                                &lt;span style="color:green;"&gt;// d = 2;
                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                                    d,
                                    &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)
&lt;/u&gt;&lt;/strong&gt;                                ),
                                &lt;span style="color:green;"&gt;// while (true)
                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Loop(
                                    &lt;span style="color:green;"&gt;// {
                                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                        &lt;span style="color:green;"&gt;// if
                                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                                            &lt;span style="color:green;"&gt;// (!
                                            &lt;/span&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(
&lt;/u&gt;&lt;/strong&gt;                                                &lt;span style="color:green;"&gt;// d &amp;lt;= Math.Sqrt(n)
                                                &lt;/span&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.LessThanOrEqual(
&lt;/u&gt;&lt;/strong&gt;                                                    &lt;strong&gt;&lt;u&gt;d,&lt;/u&gt;&lt;/strong&gt;
                                                    &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Convert(
&lt;/u&gt;&lt;/strong&gt;                                                        &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(&lt;/u&gt;&lt;/strong&gt;
                                                            &lt;strong&gt;&lt;u&gt;&lt;span style="color:blue;"&gt;null&lt;/span&gt;,&lt;/u&gt;&lt;/strong&gt;
                                                            &lt;strong&gt;&lt;u&gt;&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Sqrt&amp;quot;&lt;/span&gt;),
&lt;/u&gt;&lt;/strong&gt;                                                            &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Convert(&lt;/u&gt;&lt;/strong&gt;
                                                                &lt;strong&gt;&lt;u&gt;n,&lt;/u&gt;&lt;/strong&gt;
                                                                &lt;strong&gt;&lt;u&gt;&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;double&lt;/span&gt;)
&lt;/u&gt;&lt;/strong&gt;                                                            &lt;strong&gt;&lt;u&gt;)&lt;/u&gt;&lt;/strong&gt;
                                                        &lt;strong&gt;&lt;u&gt;),&lt;/u&gt;&lt;/strong&gt;
                                                        &lt;strong&gt;&lt;u&gt;&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;)
&lt;/u&gt;&lt;/strong&gt;                                                    &lt;strong&gt;&lt;u&gt;)&lt;/u&gt;&lt;/strong&gt;
                                                &lt;strong&gt;&lt;u&gt;)&lt;/u&gt;&lt;/strong&gt;
                                            &lt;span style="color:green;"&gt;// )
                                            &lt;/span&gt;&lt;strong&gt;&lt;u&gt;)&lt;/u&gt;&lt;/strong&gt;,
                                            &lt;span style="color:green;"&gt;// break;
                                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
                                        ),
                                        &lt;span style="color:green;"&gt;// {
                                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                            &lt;span style="color:green;"&gt;// if (n % d == 0)
                                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                                                &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Equal(
&lt;/u&gt;&lt;/strong&gt;                                                    &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Modulo(
&lt;/u&gt;&lt;/strong&gt;                                                        &lt;strong&gt;&lt;u&gt;n,&lt;/u&gt;&lt;/strong&gt;
                                                        &lt;strong&gt;&lt;u&gt;d&lt;/u&gt;&lt;/strong&gt;
                                                    &lt;strong&gt;&lt;u&gt;),&lt;/u&gt;&lt;/strong&gt;
                                                    &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(0)
&lt;/u&gt;&lt;/strong&gt;                                                &lt;strong&gt;&lt;u&gt;)&lt;/u&gt;&lt;/strong&gt;,
                                                &lt;span style="color:green;"&gt;// {
                                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                                    &lt;span style="color:green;"&gt;// found = true;
                                                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                                                        found,
                                                        &lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue;"&gt;true&lt;/span&gt;)&lt;/u&gt;&lt;/strong&gt;
                                                    ),
                                                    &lt;span style="color:green;"&gt;// break;
                                                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
                                                &lt;span style="color:green;"&gt;// }
                                                &lt;/span&gt;)
                                            )
                                        &lt;span style="color:green;"&gt;// }
                                        &lt;/span&gt;),
                                        &lt;span style="color:green;"&gt;// d++;
                                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.PostIncrementAssign(d)
                                    &lt;span style="color:green;"&gt;// }
                                    &lt;/span&gt;),
                                    breakInner
                                )
                            ),
                            &lt;span style="color:green;"&gt;// if
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                                &lt;span style="color:green;"&gt;// (!found)
                                &lt;/span&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(found)&lt;/u&gt;&lt;/strong&gt;,
                                &lt;span style="color:green;"&gt;//    res.Add(n);
                                &lt;/span&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
&lt;/u&gt;&lt;/strong&gt;                                    &lt;strong&gt;&lt;u&gt;res,&lt;/u&gt;&lt;/strong&gt;
                                    &lt;strong&gt;&lt;u&gt;&lt;span style="color:blue;"&gt;typeof&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;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Add&amp;quot;&lt;/span&gt;),
&lt;/u&gt;&lt;/strong&gt;                                    &lt;strong&gt;&lt;u&gt;n&lt;/u&gt;&lt;/strong&gt;
                                &lt;strong&gt;&lt;u&gt;)&lt;/u&gt;&lt;/strong&gt;
                            )
                        ),
                        &lt;span style="color:green;"&gt;// n++;
                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.PostIncrementAssign(n)
                    &lt;span style="color:green;"&gt;// }
                    &lt;/span&gt;),
                    breakOuter
                )
            ),
            res
        ),
        to
    &lt;span style="color:green;"&gt;// }
    &lt;/span&gt;).Compile();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;I’ve formatted a bunch of nodes in the expression tree above to indicate the “tiles” that are based on the v3.0 subset of the Expression Tree APIs, which do have language support. What if we could simplify the declaration above by leveraging the language support at places where it’s worthwhile? A tour through simplifying statement trees…&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Abstraction + application = ???&lt;/h1&gt;

&lt;p&gt;Without much further ado, let’s dive straight into our pool of expression tree tricks and reveal the goods for this round: abstraction and application. Guess what, we’re back to fundamental lambda calculus. An explanation is in order:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Abstraction&lt;/strong&gt; is the act of abstracting over an expression, i.e. introducing a parameterized function. Given an expression, turning a symbol therein into a parameter is what it takes to &lt;em&gt;abstract over the expression&lt;/em&gt;: 

    &lt;br /&gt;

    &lt;br /&gt;&lt;a href="http://bartdesmet.info/images_wlw/StatementTreesWithLessPainFollowUponSy.0_6F14/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/StatementTreesWithLessPainFollowUponSy.0_6F14/image_thumb.png" width="370" height="50" /&gt;&lt;/a&gt; 

    &lt;br /&gt;&lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Application &lt;/strong&gt;is also known as beta-reduction and corresponds to the act of applying a function given one or more arguments (strictly speaking one at a time): 

    &lt;br /&gt;

    &lt;br /&gt;&lt;a href="http://bartdesmet.info/images_wlw/StatementTreesWithLessPainFollowUponSy.0_6F14/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/StatementTreesWithLessPainFollowUponSy.0_6F14/image_thumb_3.png" width="484" height="52" /&gt;&lt;/a&gt;&amp;#160; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Given those fundamental laws in lambda calculus, we can create a very round-about way of expressing 1 + 2. Just reverse the arrows in the last diagram: 2 becomes y, 1 becomes x, both “abstracting away” the constants one at a time, resulting in a function that’s readily applied to the two constants.&lt;/p&gt;

&lt;p&gt;This basic insight is what will help us to simplify the statement tree declaration, allowing us to “tile in” expression trees in the bigger soup of statement tree nodes. But before we go there, let’s show the technique above in practice. Say we want to over-complicate the act of adding 1 and 2 together and do so through a deviation along the road of abstraction and application:&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;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &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;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;f = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;(
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(x, y),
    x, y
);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;three = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(
    f,
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1),
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)
);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;(three).Compile();

&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(res());&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;What’s happening here is not that difficult as it may seem at first glance. The “f” lambda expression simply is a function that goes from x and y to x + y (in C# lingo, (x, y) =&amp;gt; x + y). Expression.Invoke is used to invoke a delegate (lambdas ultimately are delegates), this time supplying the arguments. So, “three” is shorthand for ((x, y) =&amp;gt; x + y)(1, 2), which is &lt;em&gt;longhand&lt;/em&gt; for 1 + 2. Finally, the “res” lambda expression is a simple function returning an int, being the result of the invocation of the sum abstraction.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/StatementTreesWithLessPainFollowUponSy.0_6F14/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/StatementTreesWithLessPainFollowUponSy.0_6F14/image_thumb_4.png" width="518" height="289" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Looking at the generated IL code for the “res” delegate (using the tricks revealed in the previous post), we see the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;IL_0000: ldc.i4.1 
      &lt;br /&gt;IL_0001: ldc.i4.2 

      &lt;br /&gt;IL_0002: stloc.1 

      &lt;br /&gt;IL_0003: stloc.0 

      &lt;br /&gt;IL_0004: ldloc.0 

      &lt;br /&gt;IL_0005: ldloc.1 

      &lt;br /&gt;IL_0006: add 

      &lt;br /&gt;IL_0007: ret &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Did you see it? You did? Great! Exactly, no single trace of a delegate call in here. The combination of application (InvocationExpression) over an abstraction (LambdaExpression) got optimized away. Instead of pushing constants 1 and 2 on the stack in preparation of a delegate invocation call instruction, they get stored in locals, followed by a dump of the invoked function’s IL where the expected ldarg instructions are replaced by ldloc instructions. All in all, it’s still as if we’d written:&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:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;(
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(
        &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1),
        &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)
    )
).Compile();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;which translates in slightly simpler IL code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;IL_0000: ldc.i4.1 
      &lt;br /&gt;IL_0001: ldc.i4.2 

      &lt;br /&gt;IL_0002: add 

      &lt;br /&gt;IL_0003: ret &lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Eliminating the excessive stloc/ldloc pairs in the original fragment is something the JIT compiler could take care of it feels happy to do so, but the core message here is that this trick of “abstract &amp;amp; apply” is cheaper than it looks.&lt;/p&gt;

&lt;p&gt;Why am I telling you all of this? In fact, the trick outlined above is what we’ll use to tile in language-generated expression trees in a bigger sea of hand-crafted statement trees. For the sample above, what if we made the function definition through abstraction happen using the language-level support, while keeping the invocation call in plain hand-crafted expression trees:&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;three = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(
    &lt;strong&gt;&lt;u&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;)((x, y) =&amp;gt; x + y)&lt;/u&gt;&lt;/strong&gt;,
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1),
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)
);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;(three).Compile();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;See it coming? Think about it for a while: we’re combining a compiler-generated expression tree with a manually created bigger one in which we embed the smaller one.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Theory applied&lt;/h1&gt;

&lt;p&gt;To keep things a bit more controlled, focus on one part of the original statement tree:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
    &lt;span style="color:green;"&gt;// (!
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(
        &lt;span style="color:green;"&gt;// d &amp;lt;= Math.Sqrt(n)
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.LessThanOrEqual(
            d,
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Convert(
                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
                    &lt;span style="color:blue;"&gt;null&lt;/span&gt;,
                    &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Sqrt&amp;quot;&lt;/span&gt;),
                    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Convert(
                        n,
                        &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;double&lt;/span&gt;)
                    )
                ),
                &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;)
            )
        )
    &lt;span style="color:green;"&gt;// )
    &lt;/span&gt;),
    &lt;span style="color:green;"&gt;// break;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
),&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This corresponds to the terminating condition for the inner loop:&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;int &lt;/span&gt;d = 2; &lt;strong&gt;&lt;u&gt;d &amp;lt;= &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Sqrt(n)&lt;/u&gt;&lt;/strong&gt;; d++)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(n % d == 0)
    {
        found = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;As we all know, that’s a plain old valued expression that could be turned into a function as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; cond = (x, y) =&amp;gt; x &amp;lt;= &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Sqrt(y);&lt;/u&gt;&lt;/strong&gt;
&lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;d = 2; &lt;strong&gt;&lt;u&gt;cond(d, n)&lt;/u&gt;&lt;/strong&gt;; d++)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(n % d == 0)
    {
        found = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we’re getting somewhere. The code above is exactly the same as the original one, but we’ve abstracted over the condition by turning it into a function of its own, which we subsequently apply given d and n. For regular code, that doesn’t make much sense, but it’s exactly the trick we’re talking about here and that will make the expression tree case simpler. What if we translated the code above as follows?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;strong&gt;&lt;u&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;/u&gt;&lt;/strong&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt;&lt;strong&gt;&lt;u&gt;&amp;gt;&lt;/u&gt;&lt;/strong&gt; cond = (x, y) =&amp;gt; x &amp;lt;= &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Sqrt(y);
&lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;d = 2; cond&lt;strong&gt;&lt;u&gt;.Compile()&lt;/u&gt;&lt;/strong&gt;(d, n); d++)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(n % d == 0)
    {
        found = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
        &lt;span style="color:blue;"&gt;break&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Heh, there’s our expression tree for the condition. As we’re still not generating the whole for-loop in a statement tree, we have to call Compile explicitly on the intermediate lambda expression to invoke it in the condition part of the for-loop. Now we can take it one step further and go back to the expression tree for the whole for-loop, patching it up with our intermediate “cond” expression tree … using application. At the same time, we can eat the “Not” node:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
    &lt;span style="color:green;"&gt;// (!
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(
        &lt;span style="color:green;"&gt;// d &amp;lt;= Math.Sqrt(n)
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.LessThanOrEqual(
            d,
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Convert(
                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
                    &lt;span style="color:blue;"&gt;null&lt;/span&gt;,
                    &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Sqrt&amp;quot;&lt;/span&gt;),
                    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Convert(
                        n,
                        &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;double&lt;/span&gt;)
                    )
                ),
                &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;)
            )
        )
    &lt;span style="color:green;"&gt;// )
    &lt;/span&gt;),
    &lt;span style="color:green;"&gt;// break;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
),&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;In essence, the first argument to IfThen (i.e. the if-statement’s condition expression) contains two variables from the outer scope: d and n. We’ll abstract over those, introducing an intermediate lambda expression, and invoke (apply) that one using d and n. Code is worth a thousand words:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
    &lt;span style="color:green;"&gt;// (!(d &amp;lt;= Math.Sqrt(n)))
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(
        &lt;strong&gt;&lt;u&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;)((x, y) =&amp;gt; !(x &amp;lt;= &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Sqrt(y)))&lt;/u&gt;&lt;/strong&gt;,
        d,
        n
    ),
    &lt;span style="color:green;"&gt;// break;
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
),&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Wow, that got a bit simpler, didn’t it? The formatted (bold, underline) part corresponds to the language-generated expression tree. All we have to do is wrap that thing in an InvocationExpression, passing in d and n as arguments (respectively being bound to x and y).&lt;/p&gt;

&lt;p&gt;Similarly, we can simplify other parts of the statement tree. For example:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// if (n % d == 0)&lt;br /&gt;&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Equal(
        &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Modulo(
            n,
            d
        ),
        &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(0)
    ),
    &lt;span style="color:green;"&gt;// {
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
        &lt;span style="color:green;"&gt;// found = true;
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
            found,
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue;"&gt;true&lt;/span&gt;)
        ),
        &lt;span style="color:green;"&gt;// break;
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
    &lt;span style="color:green;"&gt;// }
    &lt;/span&gt;)
)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;It doesn’t make sense to try to abstract Expression.Constant calls (it would only blow up the code size and make things more cumbersome), but the n % d == 0 part is something we could ask the compiler to generate for us:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// if (n % d == 0)
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(    
        &lt;strong&gt;&lt;u&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;)((x, y) =&amp;gt; x % y == 0)&lt;/u&gt;&lt;/strong&gt;,
        n,
        d
    ),
    &lt;span style="color:green;"&gt;// {
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
        &lt;span style="color:green;"&gt;// found = true;
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
            found,
            &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue;"&gt;true&lt;/span&gt;)
        ),
        &lt;span style="color:green;"&gt;// break;
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
    &lt;span style="color:green;"&gt;// }
    &lt;/span&gt;)
)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;It’s a little unfortunate lambda expressions need to have a type forced upon them to emit them either as a delegate (Func&amp;lt;…&amp;gt; types) or an expression tree (Expression&amp;lt;Func&amp;lt;…&amp;gt;&amp;gt; types), requiring us to use an explicit cast to demand the compiler to generate an expression tree. This blows up the code significantly, but still we’re saving quite a bit of code. Also for method invocations, we can get rid of the ugly reflection code required to get the right overload, e.g.:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// if
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
    &lt;span style="color:green;"&gt;// (!found)
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(found),
    &lt;span style="color:green;"&gt;//    res.Add(n);
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(
        res,
        &lt;span style="color:blue;"&gt;typeof&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;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Add&amp;quot;&lt;/span&gt;),
        n
    )
)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Finding the Add method is simple in this case, but if you end up creating a MethodCallExpression with a bunch of arguments to a method with lots of overloads available, the code gets quite complicated. In the sample above, there’s little to gain, but just for the sake of illustration:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// if
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
    &lt;span style="color:green;"&gt;// (!found)
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(found),
    &lt;span style="color:green;"&gt;//    res.Add(n);
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(
        &lt;strong&gt;&lt;u&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&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;int&lt;/span&gt;&amp;gt;&amp;gt;)((l, e) =&amp;gt; l.Add(e))&lt;/u&gt;&lt;/strong&gt;,
        res,
        n
    )
)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Moreover, when typing the lambda expression above you’ll get full-blown (statically typed) IntelliSense:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/StatementTreesWithLessPainFollowUponSy.0_6F14/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/StatementTreesWithLessPainFollowUponSy.0_6F14/image_thumb_5.png" width="643" height="161" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In fact, this trick is a runtime-aided trick to implement an “infoof” operator (info-of) which I use from time to time. For example, if you want to get the MethodInfo for Console.WriteLine(“{0} is {1}”, “Bart”, 26) that can get quite involved using reflection flags (public, static), a method name in a string (“WriteLine”), a type array for the arguments (beware of the “params” behavior above), etc. Instead, you could do this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodInfo &lt;/span&gt;InfoOf(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;gt; ex)
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;mce = ex.Body &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallExpression&lt;/span&gt;;
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(mce != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;mce.Method;
    }
    &lt;span style="color:blue;"&gt;else
    &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;InfoOf called on expression without any kind of member access.&amp;quot;&lt;/span&gt;);
    }
}

&lt;span style="color:blue;"&gt;static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemberInfo &lt;/span&gt;InfoOf&amp;lt;T&amp;gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; ex)
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;me = ex.Body &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MemberExpression&lt;/span&gt;;
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(me != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;me.Member;
    }
    &lt;span style="color:blue;"&gt;else
    &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;InfoOf called on expression without any kind of member access.&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;which we can call as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;cw = InfoOf(() =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;{0} is {1}&amp;quot;&lt;/span&gt;, &lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 26));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;now = InfoOf(() =&amp;gt; &lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;So, all in all, the lack of statement tree support in the language is a pity, but by leveraging existing expression tree support we can simplify the task at hand in some cases. The result for our sample is as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;to = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Parameter(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;to&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&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:#a31515;"&gt;&amp;quot;res&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;n = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;n&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;found = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;bool&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;found&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;d = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Variable(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;int&lt;/span&gt;), &lt;span style="color:#a31515;"&gt;&amp;quot;d&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;breakOuter = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Label();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;breakInner = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Label();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;getPrimes = 
    &lt;span style="color:green;"&gt;// Func&amp;lt;int, List&amp;lt;int&amp;gt;&amp;gt; getPrimes =
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&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;&amp;gt;&amp;gt;(
        &lt;span style="color:green;"&gt;// {
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
            &lt;span style="color:green;"&gt;// List&amp;lt;int&amp;gt; res;
            &lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { res },
            &lt;span style="color:green;"&gt;// res = new List&amp;lt;int&amp;gt;();
            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                res,
                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.New(&lt;span style="color:blue;"&gt;typeof&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:green;"&gt;// {
            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                &lt;span style="color:green;"&gt;// int n;
                &lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { n },
                &lt;span style="color:green;"&gt;// n = 2;
                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                    n,
                    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)
                ),
                &lt;span style="color:green;"&gt;// while (true)
                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Loop(
                    &lt;span style="color:green;"&gt;// {
                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                        &lt;span style="color:green;"&gt;// if
                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                            &lt;span style="color:green;"&gt;// (!
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(
                                &lt;span style="color:green;"&gt;// (n &amp;lt;= to)
                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.LessThanOrEqual(
                                    n,
                                    to
                                )
                            &lt;span style="color:green;"&gt;// )
                            &lt;/span&gt;),
                            &lt;span style="color:green;"&gt;// break;
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakOuter)
                        ),
                        &lt;span style="color:green;"&gt;// {
                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                            &lt;span style="color:green;"&gt;// bool found;
                            &lt;/span&gt;&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { found },
                            &lt;span style="color:green;"&gt;// found = false;
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                                found,
                                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue;"&gt;false&lt;/span&gt;)
                            ),
                            &lt;span style="color:green;"&gt;// {
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                &lt;span style="color:green;"&gt;// int d;
                                &lt;/span&gt;&lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { d },
                                &lt;span style="color:green;"&gt;// d = 2;
                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                                    d,
                                    &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)
                                ),
                                &lt;span style="color:green;"&gt;// while (true)
                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Loop(
                                    &lt;span style="color:green;"&gt;// {
                                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                        &lt;span style="color:green;"&gt;// if
                                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                                            &lt;span style="color:green;"&gt;// (!(d &amp;lt;= Math.Sqrt(n)))
                                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(
                                                &lt;strong&gt;&lt;u&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;)((x, y) =&amp;gt; !(x &amp;lt;= &lt;span style="color:#2b91af;"&gt;Math&lt;/span&gt;.Sqrt(y)))&lt;/u&gt;&lt;/strong&gt;,
                                                d,
                                                n
                                            ),
                                            &lt;span style="color:green;"&gt;// break;
                                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
                                        ),
                                        &lt;span style="color:green;"&gt;// {
                                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                            &lt;span style="color:green;"&gt;// if (n % d == 0)
                                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                                                &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(    
                                                    &lt;strong&gt;&lt;u&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt;&amp;gt;)((x, y) =&amp;gt; x % y == 0)&lt;/u&gt;&lt;/strong&gt;,
                                                    n,
                                                    d
                                                ),
                                                &lt;span style="color:green;"&gt;// {
                                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Block(
                                                    &lt;span style="color:green;"&gt;// found = true;
                                                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Assign(
                                                        found,
                                                        &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(&lt;span style="color:blue;"&gt;true&lt;/span&gt;)
                                                    ),
                                                    &lt;span style="color:green;"&gt;// break;
                                                    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Break(breakInner)
                                                &lt;span style="color:green;"&gt;// }
                                                &lt;/span&gt;)
                                            )
                                        &lt;span style="color:green;"&gt;// }
                                        &lt;/span&gt;),
                                        &lt;span style="color:green;"&gt;// d++;
                                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.PostIncrementAssign(d)
                                    &lt;span style="color:green;"&gt;// }
                                    &lt;/span&gt;),
                                    breakInner
                                )
                            ),
                            &lt;span style="color:green;"&gt;// if
                            &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.IfThen(
                                &lt;span style="color:green;"&gt;// (!found)
                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Not(found),
                                &lt;span style="color:green;"&gt;//    res.Add(n);
                                &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(
                                    &lt;strong&gt;&lt;u&gt;(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&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;int&lt;/span&gt;&amp;gt;&amp;gt;)((l, e) =&amp;gt; l.Add(e))&lt;/u&gt;&lt;/strong&gt;,
                                    res,
                                    n
                                )
                            )
                        ),
                        &lt;span style="color:green;"&gt;// n++;
                        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.PostIncrementAssign(n)
                    &lt;span style="color:green;"&gt;// }
                    &lt;/span&gt;),
                    breakOuter
                )
            ),
            res
        ),
        to
    &lt;span style="color:green;"&gt;// }
    &lt;/span&gt;).Compile();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Still quite involved to write, but a bit simpler than our previous attempt. As an exercise, identify a few other potential rewrite sites in the fragment above. Have fun!&lt;/p&gt;&lt;img src="http://blog.bartdesmet.net/aggbug.aspx?PostID=14657" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/.NET+Framework+v4.0/default.aspx">.NET Framework v4.0</category></item><item><title>C# 4.0 Feature Focus – Part 4 – Co- and Contra-Variance for Generic Delegate and Interface Types</title><link>http://blog.bartdesmet.net/blogs/bart/archive/2009/04/13/c-4-0-feature-focus-part-4-generic-co-and-contra-variance-for-delegate-and-interface-types.aspx</link><pubDate>Mon, 13 Apr 2009 07:41:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14377</guid><dc:creator>bart</dc:creator><slash:comments>19</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14377</wfw:commentRss><comments>http://blog.bartdesmet.net/blogs/bart/archive/2009/04/13/c-4-0-feature-focus-part-4-generic-co-and-contra-variance-for-delegate-and-interface-types.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx"&gt;Last time&lt;/a&gt; around in this series, I promised to talk about generic co- and contra-variance. So that’s why we’re here today. In this post I’ll explain the theoretical concepts behind these fancy-sounding terms, look at the runtime’s take on it, show how to use them in C# 4.0 and most important of all: tell you why you don’t have to worry about all of this :-).&lt;/p&gt;
&lt;h1&gt;What’s variance?&lt;/h1&gt;
&lt;p&gt;Language features with names like variance ought to come from a theoretical background, don’t you think so? Absolutely right, and that’s no different for variance with category theory being its source of inspiration. Although we often speak about co- and contra-variance (turns out C# – amongst lots of other languages – already use those concepts , as we’ll see later) there are three sorts of variance to be explained before moving on.&lt;/p&gt;
&lt;h2&gt;Type ordering&lt;/h2&gt;
&lt;p&gt;First we need to establish the notion of &lt;strong&gt;type ordering&lt;/strong&gt;. All of you know about object-oriented programming where types are used to indicate the “kind” of data one is dealing with. On top of this, subtyping is used to specialize types. Or, the other way around, operations supported on a supertype can also be applied to its subtypes (possibly with a specialized implementation through overriding and virtual method dispatch).&lt;/p&gt;
&lt;p&gt;For example, System.Object has a ToString method. System.DateTime is a subtype of System.Object and therefore also has a ToString method on it (either derived from the base type as-is or overridden, but that doesn’t matter for now).&lt;/p&gt;
&lt;p&gt;Let’s use more concise notation to write down such relationships. If D(erived) is a subclass of B(ase), we’ll write &lt;strong&gt;D &amp;lt;: B&lt;/strong&gt;. To say d is an instance of D, we’ll write &lt;strong&gt;d : D&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Based on this we can start formulating properties, such as &lt;strong&gt;subsumption&lt;/strong&gt;, the formal notion of subtype-relationships:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If d : D and D &amp;lt;: B, then d : B&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;For instance, if we substitute d for name, D for System.String and B for System.Object, we end up with:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If name : System.String and System.String &amp;lt;: System.Object, then name : System.Object&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;We all know this: because name is declared to be a string and the string type is a subtype of object, we can say name ought to be an object. The notation &amp;lt;: is what we call type ordering. I’ll leave it to the math-savvy reader to map those concepts back to the properties of binary relations, such as reflexivity, (anti)-symmetry and transitivity.&lt;/p&gt;
&lt;h2&gt;Variance&lt;/h2&gt;
&lt;p&gt;What’s up with variance? In short, variance is a property of operators that act on types. This is very abstract, but we’ll make it very concrete in just a second. For now, think of it very generally: assume op(T1, T2) is an operator “that does something with/based on” T1 and T2 which are both types. For mathematicians (and programmers as it turns out) it makes perfect sense to attribute properties to that operator, capturing its behavior with respect to the types it acts on.&lt;/p&gt;
&lt;p&gt;To make things a bit more concrete, let’s map the concept of operators onto generics. (Note for geeks only. Generics are a form of “parametric polymorphism”, which extends the lambda calculus to something known as &lt;a href="http://www.cs.kun.nl/~erikpoll/ftfjp/2002/KennedySyme.pdf"&gt;System F&lt;/a&gt;.) As we know, generics allow for type parameterization. Below is a simple example introducing a Pair type:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#008080"&gt;Pair&lt;/font&gt;&amp;lt;TFirst, TSecond&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public &lt;/font&gt;Pair(TFirst first, TSecond second) &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; First = first; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Second = second; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public &lt;/font&gt;TFirst First { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public &lt;/font&gt;TSecond Second { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; &lt;font color="#0000ff"&gt;private set&lt;/font&gt;; } &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;You can think of this type declaration as an operator that, given type values for TFirst and TSecond, can give us a constructed type back (in other words, it’s a &lt;strong&gt;type constructor&lt;/strong&gt;, in the &lt;a href="http://www.haskell.org/haskellwiki/Constructor"&gt;Haskell sense&lt;/a&gt;, not the &lt;a href="http://msdn.microsoft.com/en-us/library/ms229018.aspx"&gt;CLR sense&lt;/a&gt;). Now we want to be able to express type ordering relationships over such constructed generic types. For example, how does Pair&amp;lt;string, int&amp;gt; relate to Pair&amp;lt;string, object&amp;gt; or to Pair&amp;lt;DateTime, int&amp;gt; or to … whatever. More specifically, we want to be able to infer the relationship between any Pair&amp;lt;T1, T2&amp;gt; and Pair&amp;lt;T3, T4&amp;gt; from relationships between the parameters.&lt;/p&gt;
&lt;p&gt;For instance, can we say (this is a question, not an answer just yet…) that:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If T1 &amp;lt;: T3 and T2 &amp;lt;: T4, then Pair&amp;lt;T1,T2&amp;gt; &amp;lt;: Pair&amp;lt;T3,T4&amp;gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;These are the kind of questions asked by theorists, but obviously by developers today as well.&lt;/p&gt;
&lt;h2&gt;Covariance&lt;/h2&gt;
&lt;p&gt;Time to dive into the first kind of variance: covariance. Co as a prefix means “together with”. It means an operator &lt;strong&gt;preserves the ordering of types&lt;/strong&gt;, when compared to its operands. Let me give a concrete sample, based on our Pair class above.&lt;/p&gt;
&lt;p&gt;If you know that Apple is a subtype of Fruit (Apple &amp;lt;: Fruit) and Tomato is a subtype of Vegetable (Tomato &amp;lt;: Vegetable), can you also say that Pair&amp;lt;Apple, Tomato&amp;gt; is a subtype of Pair&amp;lt;Fruit, Vegetable&amp;gt;? Looks like that ought to be valid on first sight, no? But there might be some hidden caveats… We’ll get to that soon.&lt;/p&gt;
&lt;p&gt;The formalized notion of covariance can be stated as follows:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Operator op(T1, …, Tn) is covariant in Ti (1 &amp;lt;= i &amp;lt;= n) if Si &lt;strong&gt;&lt;font color="#004000"&gt;&amp;lt;:&lt;/font&gt;&lt;/strong&gt; Ti implies op(T1, …, Ti-1, Si, Ti+1, …, Tn) &lt;strong&gt;&lt;font color="#004000"&gt;&amp;lt;:&lt;/font&gt;&lt;/strong&gt; op(T1, …, Tn)&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;A very practical case where this comes up is with sequences. For instance, given a LINQ query that returns a sequence of Student objects, can we treat that sequence as one of Person objects, i.e.:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Person&lt;/font&gt;&amp;gt; people = &lt;font color="#0000ff"&gt;from &lt;/font&gt;&lt;font color="#008080"&gt;Student &lt;/font&gt;s &lt;font color="#0000ff"&gt;in &lt;/font&gt;db.Students &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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&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="#0000ff"&gt;where&lt;/font&gt; s.Age &amp;lt;= 25 &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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&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="#0000ff"&gt;select &lt;/font&gt;s;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Today, in C# 3.0, you cannot do this because IEnumerable&amp;lt;T&amp;gt; is not covariant in T.&lt;/p&gt;
&lt;h2&gt;Contravariance&lt;/h2&gt;
&lt;p&gt;The opposite of “co” is “contra” which means “against”. In the context of variance it means an operator &lt;strong&gt;reverses the ordering of types&lt;/strong&gt;, when compared to its operands. Again a concrete sample is more than welcome I guess.&lt;/p&gt;
&lt;p&gt;Let’s stick with fruits. We known – just repeating this obvious fact – that Apple is a subtype of Fruit (Apple &amp;lt;: Fruit). Now say if we want to carry out comparison between apples (IComparer&amp;lt;Apple&amp;gt;), is it possible then to use a comparison between fruits instead (IComparer&amp;lt;Fruit&amp;gt;)? Looks like that should be possible, right? Everything that can handle two pieces of fruit for comparison ought to be able to handle two apples as each apple is a piece of fruit.&lt;/p&gt;
&lt;p&gt;The formalized notion of contravariance can be stated as follows:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Operator op(T1, …, Tn) is contravariance in Ti (1 &amp;lt;= i &amp;lt;= n) if Si &lt;strong&gt;&lt;font color="#004000"&gt;&amp;lt;: &lt;/font&gt;&lt;/strong&gt;Ti implies op(T1, …, Ti-1, Si, Ti+1, …, Tn) &lt;strong&gt;&lt;font color="#800000"&gt;:&amp;gt;&lt;/font&gt;&lt;/strong&gt; op(T1, …, Tn)&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;A very practical case where this comes up is with action delegates. For instance, given an action that takes in a Person, can we treat that action as one that deals with a Student object instead, i.e.:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Student&lt;/font&gt;&amp;gt; submitLetter = (&lt;font color="#008080"&gt;Person &lt;/font&gt;p) =&amp;gt; {&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; SendMailTo(p.HomeAddress); &lt;br /&gt;};&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;font color="#ff0000"&gt;
&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; I made a mistake in my original post, where I swapped Person and Student in the sample above. Guess it was getting late and despite&amp;nbsp;double-checking all uses of the terminology, it slipped through.&amp;nbsp;Thanks to Chris for pointing this out!&lt;/p&gt;&lt;/font&gt;
&lt;p&gt;Today, in C# 3.0, you cannot do this because Action&amp;lt;T&amp;gt; is not contravariant in T.&lt;/p&gt;
&lt;h1&gt;Broken array variance&lt;/h1&gt;
&lt;p&gt;First a shock to the reader: arrays in the CLR are covariant. “So what?”, you might wonder. Well, and here comes the shock, it turns out covariant use of arrays is not type-safe. (Let you heartbeat go down before reading on.) We’ll get to why covariant treatment of arrays is broken, but first some history. You might assume this “broken array variance” was put in the CLI (Common Language Infrastructure, the standardized specification of the CLR, &lt;a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm"&gt;ECMA-335&lt;/a&gt;) intentionally. The mission of the CLI was – and still is, bigger than ever with the whole DLR on top of it – to accommodate executing different languages on the same unified runtime with a unified type system, instruction set, runtime services, etc. One such language was Java, which has &lt;a href="http://c2.com/cgi/wiki?JavaArraysBreakTypeSafety"&gt;broken array covariance&lt;/a&gt;, and being able to accommodate that language won over fixing this behavior.&lt;/p&gt;
&lt;p&gt;But what makes arrays unsafe for covariance? Another sample with fruits… The story of the fruit farmer.&lt;/p&gt;
&lt;p&gt;A fruit farmer produces apples and has a contract with a local grocery store to sell the apples. To do so, the farmer hands over an &lt;em&gt;array of &lt;/em&gt;apples to the store. The contract states the store can return the apples that haven’t been sold in the next week, and only the apples that were sold (indicated by empty spots in the array from which the pieces of fruit have been taken) will be billed. The remainder apples – possible rotten by now – are sent to a juice factory nearby that creates sweet apple juice. This scheme is illustrated below:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/C4.0FeatureFocusPart4GenericCoandContraV_11E73/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/C4.0FeatureFocusPart4GenericCoandContraV_11E73/image_thumb.png" width="582" height="480" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;But because arrays are covariant, the grocery story (on the right) can treat an array of Apples (Apple[]) as if it were an array of Fruits (Fruit[]). Since the cells of arrays are writeable, this opens up a potential hole in the system. What if the grocery store wants to cheat and put some rotten tomatoes in the tray (let’s assume tomatoes are fruits for sake of this discussion; if you don’t agree with this, substitute “rotten tomato” for “rotten lemon” but that doesn’t sound as bad IMO, hence the use of tomatoes). The contract with the farmer stated that only the number of empty places in the tray will be considered in billing the grocery story; so fill a few empty places with unsellable rotten tomatoes and the price gets reduced. This might go unnoticed if the farmer doesn’t enforce &lt;em&gt;runtime fruit/vegetable type safety&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;If the contract with the juice factory states that only Apple-arrays can be passed in, but this didn’t get checked by the farmer at runtime after return from the grocery store, their juice will now contain tomato juice as well (a strange combination I guess). Or worse, the juice factory will blow up because the apple peeling machine expects a certain toughness from the apple being peeled and tomatoes are much softer (note: I don’t know anything at all about the factory process involved in creating juice, so I’m just fantasizing about possible horror stories).&lt;/p&gt;
&lt;p&gt;This mishap is illustrated below.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/C4.0FeatureFocusPart4GenericCoandContraV_11E73/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/C4.0FeatureFocusPart4GenericCoandContraV_11E73/image_thumb_3.png" width="582" height="480" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;But who to blame? The grocery story followed the array-based contract exactly; arrays do not prevent writing operations, so putting tomatoes in is not a violation. Clearly the farmer needs a tighter contract that ensures – statically – the grocery store cannot put other fruits or vegetables in. What the farmer should use is an “pull-based enumerating device for apples” (an IEnumerator&amp;lt;Apple&amp;gt; that is) as shown below:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/C4.0FeatureFocusPart4GenericCoandContraV_11E73/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/C4.0FeatureFocusPart4GenericCoandContraV_11E73/image_thumb_4.png" width="582" height="480" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;The spring depicts the enumerating behavior – you can only get things out but can’t push things in (ignore forceful mechanisms and ignoring the fact the spring might crush the apples :-)). Such an IEnumerable&amp;lt;T&amp;gt; is safely covariant because you can’t push anything in, so even if the farmer treats the IEnumerable&amp;lt;Apple&amp;gt; as an IEnumerable&amp;lt;Fruit&amp;gt; all he can do is get pieces of fruit (which always will happen to be apples) out.&lt;/p&gt;
&lt;p&gt;This illustrates why arrays T[] are not safely covariant and why IEnumerable&amp;lt;T&amp;gt; is. Or in code:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;namespace&lt;/font&gt; Rural.Fields &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;using &lt;/font&gt;Market; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;using &lt;/font&gt;Industry; &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;internal sealed class &lt;/font&gt;&lt;font color="#008080"&gt;Farm&lt;/font&gt; &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;private &lt;/font&gt;&lt;font color="#008080"&gt;GroceryStore &lt;/font&gt;_store = …; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;JuiceFactory &lt;/font&gt;_juice = …; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;private const decimal &lt;/font&gt;APPLE_PRICE = 0.5; &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;Apple&lt;/font&gt;[] PluckAppleTrees() { … } &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public void &lt;/font&gt;Work() &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; &lt;font color="#008080"&gt;Apple&lt;/font&gt;[] apples = PluckAppleTrees(); &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; _store.SellFruits(apples); &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;// here the array is treated covariantly! &lt;br /&gt;&lt;/font&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="#0000ff"&gt;int &lt;/font&gt;sold = apples.Where(apple =&amp;gt; apple != null).Count(); &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; _store.SendInvoice(sold * APPLE_PRICE); &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; _juice.ProduceAppleJuice(apples); &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;// here the array is treated invariantly &lt;br /&gt;&lt;/font&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _juice.SendInvoice((apples.Length – sold) * APPLE_PRICE * 0.8 &lt;font color="#008000"&gt;/* price of rotten apple */&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;br /&gt;&lt;br /&gt;&lt;font color="#0000ff"&gt;namespace&lt;/font&gt; Market &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public sealed class &lt;/font&gt;&lt;font color="#008080"&gt;GroceryStore&lt;/font&gt; &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;public void &lt;/font&gt;SellFruits(&lt;font color="#008080"&gt;Fruit&lt;/font&gt;[] fruits) { … } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public void &lt;/font&gt;SendInvoice(&lt;font color="#0000ff"&gt;decimal &lt;/font&gt;amount) { … } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;} &lt;br /&gt;&lt;br /&gt;&lt;font color="#0000ff"&gt;namespace &lt;/font&gt;Industry &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public sealed class &lt;/font&gt;&lt;font color="#008080"&gt;JuiceFactory&lt;/font&gt; &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;public void &lt;/font&gt;ProduceAppleJuice(&lt;font color="#008080"&gt;Apple&lt;/font&gt;[] apples) { … } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public void &lt;/font&gt;SendInvoice(&lt;font color="#0000ff"&gt;decimal&lt;/font&gt; amount) { … } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;To ensure type safety for covariant arrays, the CLR injects runtime type checks for every attempt to store an element in an array. If an object with a type incompatible with the array in memory is attempted to be written to the array, an ArrayTypeMismatchException occurs. In our case above, if the SellFruits method of GroceryStory would try to write a Tomato object to the array that’s passed in (as Fruit[] but that was created as an Apple array, in the PluckAppleTrees method of the Farm) the CLR would detect this and throw the exception.&lt;/p&gt;
&lt;p&gt;A more isolated sample:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;[] names = &lt;font color="#0000ff"&gt;new string&lt;/font&gt;[] { &lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, &lt;font color="#800000"&gt;“John”&lt;/font&gt; }; &lt;br /&gt;&lt;font color="#0000ff"&gt;object&lt;/font&gt;[] things = names; &lt;br /&gt;things[0] = 123;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt; // ArrayTypeMismatchException – 123 is not a string &lt;br /&gt;&lt;/font&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(names[0].ToUpper() &lt;font color="#008000"&gt;/* if the above would work, we’d call the non-existing ToUpper method on System.Int32 */&lt;/font&gt;);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;h1&gt;Today’s co- and contra-variance support&lt;/h1&gt;
&lt;p&gt;C# actually has places where co- and contra-variance principles are being used, more specifically in delegate types. A typical sample where this comes in useful is when dealing with events.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;delegate void &lt;/font&gt;&lt;font color="#008080"&gt;CancelEvent&lt;/font&gt;(&lt;font color="#0000ff"&gt;object &lt;/font&gt;sender, &lt;font color="#008080"&gt;CancelEventArgs &lt;/font&gt;e); &lt;br /&gt;&lt;font color="#0000ff"&gt;delegate void &lt;/font&gt;&lt;font color="#008080"&gt;ProgressEvent&lt;/font&gt;(&lt;font color="#0000ff"&gt;object &lt;/font&gt;sender, &lt;font color="#008080"&gt;ProgressEventArgs &lt;/font&gt;e); &lt;br /&gt;&lt;br /&gt;&lt;font color="#0000ff"&gt;sealed class &lt;/font&gt;&lt;font color="#008080"&gt;Engine&lt;/font&gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public event &lt;/font&gt;&lt;font color="#008080"&gt;CancelEvent &lt;/font&gt;Cancelled; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public event &lt;/font&gt;&lt;font color="#008080"&gt;ProgressEvent &lt;/font&gt;ProgressChanged; &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public void &lt;/font&gt;Run() { … } &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public void &lt;/font&gt;Cancel() { … } &lt;br /&gt;} &lt;br /&gt;&lt;br /&gt;&lt;font color="#0000ff"&gt;static class &lt;/font&gt;&lt;font color="#008080"&gt;Program&lt;/font&gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;Main() &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;var &lt;/font&gt;engine = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Engine&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; engine.Cancelled += Logger; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; engine.ProgressChanged += Logger; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;// run engine, etc &lt;br /&gt;&lt;/font&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;void &lt;/font&gt;Logger(&lt;font color="#0000ff"&gt;object &lt;/font&gt;sender, &lt;font color="#008080"&gt;EventArgs &lt;/font&gt;e) { … } &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Here we’re attaching an event handler to two events which have different signatures. However, the signature of Logger uses a common supertype of both events’ event arguments type, so the compiler allows this. The reason it does is because input parameters can safely be treated contravariantly. In other words, we’re getting &lt;em&gt;in&lt;/em&gt; a more derived type for the event arguments but we treat it as less derived. As the argument appears in an input position, this is safe to do.&lt;/p&gt;
&lt;p&gt;Here’s a little exercise for the reader. The following fragment compiles fine because of contravariant treatment for delegate parameters:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#008080"&gt;Contra&lt;/font&gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;Main() &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;var &lt;/font&gt;b = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; b.Event += Handler; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;Handler(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o &lt;font color="#008000"&gt;/* contravariant treatment when used with delegate type D */&lt;/font&gt;) &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;delegate void &lt;/font&gt;&lt;font color="#008080"&gt;D&lt;/font&gt;(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s); &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&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;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;public event &lt;/font&gt;&lt;font color="#008080"&gt;D &lt;/font&gt;Event; &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;However, if we change the parameter on D by adding a ref modifier, it doesn’t work anymore.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static void &lt;/font&gt;Handler(&lt;font color="#0000ff"&gt;ref object &lt;/font&gt;o &lt;font color="#008000"&gt;/* ??? */&lt;/font&gt;) &lt;br /&gt;&lt;/font&gt;&lt;font color="#0000ff"&gt;&lt;br /&gt;&lt;font face="Courier New"&gt;delegate void &lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;D&lt;/font&gt;(&lt;font color="#0000ff"&gt;ref string &lt;/font&gt;s); &lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Why? Illustrate with a sample showing why contravariant treatment would be malicious if it were allowed here…&lt;/p&gt;
&lt;h1&gt;Covariant and contravariant generic parameters in the CLI&lt;/h1&gt;
&lt;p&gt;With the second release of the CLR, as part of .NET Framework 2.0, generics were introduced based on the work done by Don Syme and Andrew Kennedy in the Gyro project. Right from the start, generic parameters have supported the declaration of desired variance behavior. Section 8 in Partition I of the ECMA-335 spec for the CLI states:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;In addition, CLI supports covariant and contravariant generic parameters, with the following characteristics:&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;It is type-safe (based on purely static checking)&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;&lt;em&gt;Simplicity: in particular, variance is only permitted on generic interfaces and generic delegates (not classes or value-types)&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;&lt;em&gt;Languages not wishing to support variance can ignore the feature, and treat all generic types as non-variant.&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;&lt;em&gt;Enable implementation of more complex covariance scheme as used in some languages, e.g. Eiffel.&lt;/em&gt; &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;but so far, C# and VB have been following the third bullet, ignoring the feature. Before we go there, we should have a look at how generics variance is surfaced through IL, proving its support in the CLR today. More information on this can be found in paragraph 9.5 of Partition II:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;The CLI supports covariance and contravariance of generic parameters, but only in the signatures of interfaces and delegate classes.&amp;nbsp; &lt;br /&gt;The symbol “+” is used in the syntax of §10.1.7 to denote a covariant generic parameter, while “-” is used to denote a contravariant generic parameter.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Our two main samples have been IEnumerable&amp;lt;T&amp;gt; and IComparer&amp;lt;T&amp;gt;. Let’s define our own interfaces for both (in C#) and see how it looks like at the level of IL:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;interface &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;T&amp;gt; GetEnumerator(); &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;interface &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;bool &lt;/font&gt;MoveNext(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; T Current { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; } &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;interface &lt;/font&gt;&lt;font color="#008080"&gt;IComparer&lt;/font&gt;&amp;lt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;int &lt;/font&gt;Compare(T arg1, T arg2); &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;By default generic interface and delegate types are invariant:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/C4.0FeatureFocusPart4GenericCoandContraV_11E73/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/C4.0FeatureFocusPart4GenericCoandContraV_11E73/image_thumb_5.png" width="400" height="328" /&gt;&lt;/a&gt; &lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;However, we can roundtrip through IL to make those types covariant (for IEnumer*&amp;lt;T&amp;gt;) or contravariant (for IComparer&amp;lt;T&amp;gt;)in their generic parameter T. The difference is subtle: adding a + (covariant) or a - (contravariant) to the generic parameter T.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;.class interface private abstract auto ansi IEnumerable`1&amp;lt;&lt;strong&gt;&lt;font color="#008000"&gt;+&lt;/font&gt;&lt;/strong&gt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp; .method public hidebysig newslot abstract virtual &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; instance class IEnumerator`1&amp;lt;!T&amp;gt; &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; GetEnumerator() cil managed &lt;br /&gt;&amp;nbsp; { &lt;br /&gt;&amp;nbsp; } // end of method IEnumerable`1::GetEnumerator &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;} // end of class IEnumerable`1 &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;.class interface private abstract auto ansi IEnumerator`1&amp;lt;&lt;strong&gt;&lt;font color="#008000"&gt;+&lt;/font&gt;&lt;/strong&gt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp; .method public hidebysig newslot abstract virtual &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; instance bool&amp;nbsp; MoveNext() cil managed &lt;br /&gt;&amp;nbsp; { &lt;br /&gt;&amp;nbsp; } // end of method IEnumerator`1::MoveNext &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; .method public hidebysig newslot specialname abstract virtual &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; instance !T&amp;nbsp; get_Current() cil managed &lt;br /&gt;&amp;nbsp; { &lt;br /&gt;&amp;nbsp; } // end of method IEnumerator`1::get_Current &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; .property instance !T Current() &lt;br /&gt;&amp;nbsp; { &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .get instance !T IEnumerator`1::get_Current() &lt;br /&gt;&amp;nbsp; } // end of property IEnumerator`1::Current &lt;br /&gt;} // end of class IEnumerator`1 &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;.class interface private abstract auto ansi IComparer`1&amp;lt;&lt;strong&gt;&lt;font color="#800000"&gt;-&lt;/font&gt;&lt;/strong&gt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp; .method public hidebysig newslot abstract virtual &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; instance int32&amp;nbsp; Compare(!T arg1, &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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; !T arg2) cil managed &lt;br /&gt;&amp;nbsp; { &lt;br /&gt;&amp;nbsp; } // end of method IComparer`1::Compare &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;} // end of class IComparer`1&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/C4.0FeatureFocusPart4GenericCoandContraV_11E73/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/C4.0FeatureFocusPart4GenericCoandContraV_11E73/image_thumb_6.png" width="400" height="330" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;Notice the ilasm tool doesn’t statically verify the correct use of variance annotations. It’s possible to mark a generic parameter as covariant while it’s used in input positions. It’s the responsibility of language compilers, e.g. for C#, to enforce such rules:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Covariant parameters should only be used in output positions: method return values, get-only properties or indexers. &lt;/li&gt;
&lt;li&gt;Contravariant parameters should only occur in input positions: method parameters, set-only properties or indexers. &lt;/li&gt;&lt;/ul&gt;
&lt;h1&gt;C# 4.0 support&lt;/h1&gt;
&lt;p&gt;Starting with C# 4.0, the language does support co- and contra-variance on generic delegate and interface type parameters. This feature has two sides to it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;As a consumer of generic interface or delegate types that behave either co- or contra-variantly, you can now do what you couldn’t do before &lt;/li&gt;&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Person&lt;/font&gt;&amp;gt; people = &lt;font color="#0000ff"&gt;from &lt;/font&gt;&lt;font color="#008080"&gt;Student &lt;/font&gt;s &lt;font color="#0000ff"&gt;in &lt;/font&gt;db.Students &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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&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="#0000ff"&gt;where&lt;/font&gt; s.Age &amp;lt;= 25 &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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&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="#0000ff"&gt;select &lt;/font&gt;s; &lt;br /&gt;&lt;br /&gt;&lt;font color="#008080"&gt;IComparer&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt; comp = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;MyObjectComparer&lt;/font&gt;(); &lt;font color="#008000"&gt;// implements IComparer&amp;lt;object&amp;gt;&lt;/font&gt;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;ul&gt;
&lt;li&gt;As a provider of generic interface or delegate types you can now specify the intended behavior. This is done using the &lt;strong&gt;out &lt;/strong&gt;and &lt;strong&gt;in &lt;/strong&gt;keywords, which respectively stand for covariant (output positions only) and contravariant (input positions only). The compiler enforces that parameters that behave in a non-invariant way are used appropriately: &lt;/li&gt;&lt;/ul&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;interface &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;out &lt;/font&gt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;T&amp;gt; GetEnumerator(); &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;interface &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;out &lt;/font&gt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;bool &lt;/font&gt;MoveNext(); &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; T Current { &lt;font color="#0000ff"&gt;get&lt;/font&gt;; } &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;interface &lt;/font&gt;&lt;font color="#008080"&gt;IComparer&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;in &lt;/font&gt;T&amp;gt; &lt;br /&gt;{ &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;font color="#0000ff"&gt;int &lt;/font&gt;Compare(T arg1, T arg2); &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;You might wonder why the compiler doesn’t infer the applicable variance annotation on behalf of the user. This could easily lead to “accidental” incorrect treatment as things evolve. Although it’s not a good idea to start changing interfaces, during development your interface types might be in flux and it would be disruptive if consumer code starts breaking all of a sudden because a generic parameter’s variance treatment has changed. It was felt it’d be better to have developers be explicit about variance.&lt;/p&gt;
&lt;p&gt;Obviously a bunch of interface and delegate types in the BCL have been modified with variance annotations. IComparer&amp;lt;T&amp;gt;, IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt; are just a few samples. Others include the Func and Action delegates:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font color="#0000ff"&gt;delegate &lt;/font&gt;R &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;in &lt;/font&gt;T1, &lt;font color="#0000ff"&gt;in &lt;/font&gt;T2, …, &lt;font color="#0000ff"&gt;in &lt;/font&gt;Tn, &lt;font color="#0000ff"&gt;out &lt;/font&gt;R&amp;gt;(T1 arg1, T2 arg2, …, Tn argn); &lt;br /&gt;&lt;font color="#0000ff"&gt;delegate void &lt;/font&gt;&lt;font color="#008080"&gt;Action&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;in &lt;/font&gt;T1, &lt;font color="#0000ff"&gt;in &lt;/font&gt;T2, …, &lt;font color="#0000ff"&gt;in &lt;/font&gt;Tn&amp;gt;(T1 arg1, T2 arg2, …, Tn argn);&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;That’s it. I told’ya it was simple, no? The good thing is, you shouldn’t really know much about all of this: &lt;strong&gt;It Just Works&lt;/strong&gt; (now also available for C# – inside joke).&lt;/p&gt;&lt;img src="http://blog.bartdesmet.net/aggbug.aspx?PostID=14377" width="1" height="1"&gt;</description><category domain="http://blog.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://blog.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://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14070</wfw:commentRss><comments>http://blog.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://blog.bartdesmet.net/aggbug.aspx?PostID=14070" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>C# 4.0 Feature Focus - Part 3 - Intermezzo: LINQ's new Zip operator</title><link>http://blog.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx</link><pubDate>Tue, 04 Nov 2008 07:11:43 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14055</guid><dc:creator>bart</dc:creator><slash:comments>23</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14055</wfw:commentRss><comments>http://blog.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx#comments</comments><description>&lt;p&gt;After &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/11/01/c-4-0-feature-focus-part-2-named-parameters.aspx"&gt;named parameters&lt;/a&gt; and &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx"&gt;optional parameters&lt;/a&gt;, we&amp;#39;ll take a little breadth and deviate a bit from the language specifics to present a new LINQ operator: Zip. Just like a zipper zips two streams of materials together, LINQ&amp;#39;s Zip operator can zip together two sequences. Here&amp;#39;s the signature of the new method:&lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func);&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Sample&lt;/h1&gt;  &lt;p&gt;Given two sequences and a function that combines two elements from both sequences, a sequence of zipped pairs is produced. Here&amp;#39;s a sample:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;[] names = { &lt;font color="#800000"&gt;&amp;quot;Bart&amp;quot;&lt;/font&gt;, &lt;font color="#800000"&gt;&amp;quot;John&amp;quot;&lt;/font&gt; };         &lt;br /&gt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;[] ages = { 25, 60 };         &lt;br /&gt;        &lt;br /&gt;names.Zip(ages, (name, age) =&amp;gt; name + &lt;font color="#800000"&gt;&amp;quot; is &amp;quot;&lt;/font&gt; + age + &lt;font color="#800000"&gt;&amp;quot; years old.&amp;quot;&lt;/font&gt;);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This produces a sequence with the sentences &amp;quot;Bart is 25 years old.&amp;quot; and &amp;quot;John is 60 years old.&amp;quot;. The lambda syntax for the passed-in function should speak for itself, and notice we&amp;#39;re using extension method invocation here, so names is propagated to become the left-hand side of the method call.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;How Zip works&lt;/h1&gt;  &lt;p&gt;Previously I&amp;#39;ve implemented the Standard Query Operators for reference purposes on the Codeplex site at &lt;a href="http://www.codeplex.com/LINQSQO"&gt;http://www.codeplex.com/LINQSQO&lt;/a&gt;. I won&amp;#39;t update that sample library just yet, but here&amp;#39;s an illustration on how easy Zip is to implement, ignoring exception handling (which is more subtle than you might think, see further):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &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;var&lt;/font&gt; ie1 = first.GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie2 = second.GetEnumerator(); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(ie1.MoveNext() &amp;amp;&amp;amp; ie2.MoveNext())         &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;yield return &lt;/font&gt;func(ie1.Current, ie2.Current);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The Zip operation is implemented using iterators inside (&amp;quot;yield return&amp;quot;) and stops as soon as one of the sequences runs out of juice (the case of the asymmetric zipper).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Zip without Zip?&lt;/h1&gt;  &lt;p&gt;As a curiosity, is it actually possible to build Zip out of existing LINQ operators, ignoring performance worries? Unsurprisingly, it turns out this is the case. Here&amp;#39;s how:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &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;return &lt;/font&gt;first.Select((x, i) =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; { X = x, I = i }).Join(second.Select((x, i) =&amp;gt; &lt;font color="#0000ff"&gt;new&lt;/font&gt; { X = x, I = i }), o =&amp;gt; o.I, i =&amp;gt; i.I, (o, i) =&amp;gt; func(o.X, i.X));         &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;(Exercise for the reader: think of more alternatives.) How does this work? To explain this we need a bit of vocabulary, so let&amp;#39;s refer to &lt;a href="http://en.wikipedia.org/wiki/Zipper"&gt;Wikipedia&lt;/a&gt; for a second and apply an isomorphism between textile sciences and computer sciences (something in me screams &amp;quot;zip, zipper, zippest&amp;quot;):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;The &lt;strike&gt;bulk&lt;/strike&gt; &lt;font color="#ff0000"&gt;signature&lt;/font&gt; of a &lt;strike&gt;zipper&lt;/strike&gt; &lt;font color="#ff0000"&gt;Zip &lt;/font&gt;consists of two &lt;strike&gt;strips&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences &lt;/font&gt;of &lt;strike&gt;fabric&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;element&lt;/font&gt; t&lt;strike&gt;&lt;font color="#ff0000"&gt;a&lt;/font&gt;&lt;/strike&gt;ype&lt;font color="#ff0000"&gt;s&lt;/font&gt;, each affixed to one of the two &lt;strike&gt;pieces&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequence instances &lt;/font&gt;to be joined, carrying tens or hundreds &lt;font color="#ff0000"&gt;or anything below OutOfMemoryException conditions&lt;/font&gt; of &lt;strike&gt;specially&lt;/strike&gt; &lt;font color="#ff0000"&gt;regularly&lt;/font&gt; &lt;strike&gt;shaped&lt;/strike&gt; &lt;font color="#ff0000"&gt;allocated&lt;/font&gt; &lt;strike&gt;metal&lt;/strike&gt; &lt;font color="#ff0000"&gt;reference-&lt;/font&gt; or &lt;strike&gt;plastic&lt;/strike&gt; &lt;font color="#ff0000"&gt;value-typed&lt;/font&gt; &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements&lt;/font&gt;. (...) The &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate&lt;/font&gt;, operated by &lt;strike&gt;hand&lt;/strike&gt; &lt;font color="#ff0000"&gt;executing Zip&lt;/font&gt;, moves along the &lt;strike&gt;rows&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences&lt;/font&gt; of &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements&lt;/font&gt;. Inside the &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate &lt;/font&gt;is a &lt;strike&gt;Y-shaped&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;strongly-typed &lt;/font&gt;&lt;strike&gt;channel&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;function&lt;/font&gt; that meshes together &lt;strike&gt;or separates&lt;/strike&gt; the opposing &lt;strike&gt;rows&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences&lt;/font&gt; of &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements&lt;/font&gt;, &lt;strike&gt;depending on the direction of its movement&lt;/strike&gt;. The &lt;strike&gt;friction&lt;/strike&gt; &lt;font color="#ff0000"&gt;binding &lt;/font&gt;and &lt;strike&gt;vibration&lt;/strike&gt; &lt;font color="#ff0000"&gt;application&lt;/font&gt; of the &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate &lt;/font&gt;&lt;strike&gt;against&lt;/strike&gt; &lt;font color="#ff0000"&gt;on &lt;/font&gt;the &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements &lt;/font&gt;causes a characteristic &lt;strike&gt;buzzing&lt;/strike&gt; &lt;font color="#ff0000"&gt;callvirt&amp;#39;ing&lt;/font&gt; noise, which is probably &lt;font color="#ff0000"&gt;not&lt;/font&gt; the origin of the name zipper. The name also may have originated in the greater speed and ease with which the two sides of a &lt;strike&gt;zipper&lt;/strike&gt; &lt;font color="#ff0000"&gt;Zip&lt;/font&gt; can be joined, compared to the time needed for &lt;strike&gt;fastening&lt;/strike&gt; &lt;font color="#ff0000"&gt;executing&lt;/font&gt; &lt;strike&gt;laces or buttons&lt;/strike&gt; &lt;font color="#ff0000"&gt;the method above&lt;/font&gt;.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Well, that&amp;#39;s exactly what happens: opposing &lt;strike&gt;rows&lt;/strike&gt; &lt;font color="#ff0000"&gt;sequences&lt;/font&gt; of &lt;strike&gt;teeth&lt;/strike&gt; &lt;font color="#ff0000"&gt;elements &lt;/font&gt;are combined by a &lt;strike&gt;Y-shaped&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;strongly-typed &lt;/font&gt;&lt;strike&gt;channel&lt;/strike&gt;&amp;#160;&lt;font color="#ff0000"&gt;function&lt;/font&gt;. How to determine opposing sequence elements? Using Select&amp;#39;s overload that provides (besides the element itself) an index denoting the element&amp;#39;s position in the original sequence. Matching the opposing elements is a matter of joining both sequences, extracting the keys (marked as I in the anonymous type) and combining the selected pairs of elements from both sequences (marked as X in the anonymous type) by feeding them in to the &lt;strike&gt;slider&lt;/strike&gt; &lt;font color="#ff0000"&gt;Func&amp;lt;TFirst, TSecond, TResult&amp;gt; delegate&lt;/font&gt;. I told you the explanation was straightforward, or did I?&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Iterators and exceptions&lt;/h1&gt;  &lt;p&gt;Most of the LINQ operators are implemented using iterators. You might wonder this this is relevant at all. Obviously we need it as LINQ operators need to be lazy. Only when you start fetching results by iterating of the sequence, the internal machinery should kick in. Declaring a query doesn&amp;#39;t cause any execution whatsoever. Internally iterators are implemented as state machines. Every state can do on &amp;quot;yield&amp;quot;, after which the state machine is suspended till the consumer asks for the next element in the sequence being produced by calling MoveNext on the IEnumerator&amp;lt;T&amp;gt; object.&lt;/p&gt;  &lt;p&gt;Our Zip implementation above is turned into an equivalent piece of code (slightly simplified for illustrative purposes):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return new &lt;/font&gt;&lt;font color="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt;(first, second, func);         &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;private sealed class &lt;/font&gt;&lt;font color="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; : &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt;, &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TResult&amp;gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;//&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// Captured iterator method parameters.          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //&lt;/font&gt;         &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; _first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; _func;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; _second;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Iterator&amp;#39;s enumerator state and thread affinity.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;State &lt;/font&gt;_state;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private int &lt;/font&gt;_initialThreadId;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Value currently yielded by the iterator&amp;#39;s enumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //&lt;/font&gt;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;TResult _current;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Local variables used by the iterator&amp;#39;s enumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TFirst&amp;gt; _ieFirst;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TSecond&amp;gt; _ieSecond;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Captured iterator method parameters used by enumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Public constructor to create an iterator in the initial ready state.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public&lt;/font&gt; ZipIterator(&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; : &lt;font color="#0000ff"&gt;this&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;this&lt;/font&gt;._first = first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._second = second;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._func = func;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Private constructor to set state and thread affinity.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;private &lt;/font&gt;ZipIterator()         &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;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Before;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._initialThreadId = &lt;font color="#008080"&gt;Thread&lt;/font&gt;.CurrentThread.ManagedThreadId;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets a new enumerator over the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TResult&amp;gt; &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt;.GetEnumerator()         &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="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; iterator;&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; // Can reuse the current enumerator if thread affinity and state permit it.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(&lt;font color="#008080"&gt;Thread&lt;/font&gt;.CurrentThread.ManagedThreadId == _initialThreadId &amp;amp;&amp;amp; _state == &lt;font color="#008080"&gt;State&lt;/font&gt;.Before)         &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; iterator = &lt;font color="#0000ff"&gt;this&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; &lt;font color="#0000ff"&gt;else&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; iterator = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;ZipIterator&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt;();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; } &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator.first = &lt;font color="#0000ff"&gt;this&lt;/font&gt;._first;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator.second = &lt;font color="#0000ff"&gt;this&lt;/font&gt;._second;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; iterator.func = &lt;font color="#0000ff"&gt;this&lt;/font&gt;._func; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;iterator;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets a new enumerator over the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;IEnumerator &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;.GetEnumerator()         &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;return&lt;/font&gt; ((&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt;)&lt;font color="#0000ff"&gt;this&lt;/font&gt;).GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Advances the iterator one yield return at a time.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;bool&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.MoveNext()         &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;switch&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._state)         &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;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Before:         &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;this&lt;/font&gt;._ieFirst = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.first.GetEnumerator();         &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;this&lt;/font&gt;._ieSecond = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.second.GetEnumerator();         &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;goto&lt;/font&gt; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&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;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended:         &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; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.MoveNext() &amp;amp;&amp;amp; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.MoveNext())         &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;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; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._current = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.func(&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.Current, &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.Current);         &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; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended;         &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; &lt;font color="#0000ff"&gt;return true&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&gt;&lt;font face="Courier New"&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;break&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.After;&lt;/font&gt;       &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return false&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Retting the iterator enumerator is not supported; create a new one instead by calling GetEnumerator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // The foreach statement does this anyway.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;void&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.Reset()         &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;throw new&lt;/font&gt; &lt;font color="#008080"&gt;NotSupportedException&lt;/font&gt;();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets the value currently yielded from the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; TResult &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;&amp;lt;TResult&amp;gt;.Current         &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;get&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;return &lt;/font&gt;_current;         &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;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Gets the value currently yielded from the iterator.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;object&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.Current         &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;get&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;return &lt;/font&gt;_current;         &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;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // IDisposable implementation.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&amp;#160;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;void&lt;/font&gt; &lt;font color="#008080"&gt;IDisposable&lt;/font&gt;.Dispose()         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;&amp;#160;&amp;#160;&amp;#160; //          &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; // Internal iterator enumerator states.           &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; //           &lt;br /&gt;&lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;private enum &lt;/font&gt;&lt;font color="#008080"&gt;State&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; Before,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Running,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Suspended,         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; After         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;font face="Courier New"&gt;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice that the code above holds the middle between the specification (paragraph 10.14 of the C# 3.0 specification) and the actual implementation in the Visual C# 2008 compiler. More specifically, I&amp;#39;ve made the discrete states (which are internally represented as integers) match the ones in the specification, but haven&amp;#39;t gone all the way in matching the code up with the &lt;/p&gt;  &lt;p&gt;Of all this machinery, the MoveNext method is the most interesting one from the iterator&amp;#39;s point of view. Here a state machine is built, rewriting the original iterator block by splitting it into discrete blocks. To perform this transformation, yield return statements are replaced as follows:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&amp;#160;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;yield &lt;/font&gt;a;&lt;/font&gt;&lt;/p&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="#0000ff"&gt;this&lt;/font&gt;._current = a;         &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;this&lt;/font&gt;&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended;         &lt;br /&gt;&lt;font color="#0000ff"&gt;return true&lt;/font&gt;;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Similar rewrites happen for yield break statements, but that&amp;#39;s not relevant here. Furthermore all the iterator block code is placed in a MoveNext method, switching on the current state. The specification only mentions the four states I&amp;#39;ve implemented above, but we&amp;#39;re lucky the number of states for our sample matches up with the number of states that&amp;#39;s specified. In cases where there are more yield statements, more states are needed to suspend the machine and resume at the same point during the next MoveNext call. Other transformations needed include rewriting of loops (things like while don&amp;#39;t really play well with suspension points and need to be rewritten in terms of if/goto, where gotos require additional states). Applying all those tricks gives us:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;bool&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.MoveNext()         &lt;br /&gt;{         &lt;br /&gt;Begin:         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;switch&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._state)         &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;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Before:         &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;this&lt;/font&gt;._ieFirst = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.first.GetEnumerator();         &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;this&lt;/font&gt;._ieSecond = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.second.GetEnumerator();         &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;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Running;         &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;goto&lt;/font&gt; Begin; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Running:&lt;/font&gt;&lt;font face="Courier New"&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended:         &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; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.MoveNext() &amp;amp;&amp;amp; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.MoveNext())         &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;this&lt;/font&gt;._current = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.func(&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.Current, &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.Current);         &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;this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.Suspended;         &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 true&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&gt;&lt;font face="Courier New"&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;break&lt;/font&gt;;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; this&lt;/font&gt;._state = &lt;font color="#008080"&gt;State&lt;/font&gt;.After;&lt;/font&gt;       &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return false&lt;/font&gt;;         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Here the local variables used in the iterator block are captured in the initial pass through MoveNext, when state is still set to Before. Strictly speaking we move from Before to Running all the way to the first point where the code gets suspended, but in our case states can be merged quite a bit. In fact the code really produced by the compiler looks like this:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;bool&lt;/font&gt; &lt;font color="#008080"&gt;IEnumerator&lt;/font&gt;.MoveNext()       &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;switch&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._state)       &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;case&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;font color="#0000ff"&gt;this&lt;/font&gt;._state = -1;       &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;this&lt;/font&gt;._ieFirst = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.first.GetEnumerator();       &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;this&lt;/font&gt;._ieSecond = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.second.GetEnumerator();       &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;while&lt;/font&gt; (&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.MoveNext() &amp;amp;&amp;amp; &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.MoveNext())       &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;this&lt;/font&gt;.current = &lt;font color="#0000ff"&gt;this&lt;/font&gt;.func(&lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieFirst.Current, &lt;font color="#0000ff"&gt;this&lt;/font&gt;._ieSecond.Current);       &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;this&lt;/font&gt;._state = 1;       &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 true&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; Resume:       &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;this&lt;/font&gt;._state = -1;       &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; &lt;font color="#0000ff"&gt;break&lt;/font&gt;; &lt;/font&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;case&lt;/font&gt; 1:         &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;goto&lt;/font&gt; Resume;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return false&lt;/font&gt;;         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;But &lt;strong&gt;why am I telling you all this&lt;/strong&gt;? Because it&amp;#39;s fascinating? Yes, for that reason too. But I promised to tell you something about exceptions, right? Let me quote from the C# 3.0 specification paragraph 10.14.4.1 first:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;em&gt;(...) The precise action performed by MoveNext depends on the state of the enumerator object when MoveNext is invoked:&lt;/em&gt;&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;em&gt;If the state of the enumerator object is &amp;#39;before&amp;#39;, invoking MoveNext:&lt;/em&gt;       &lt;ul&gt;       &lt;li&gt;&lt;em&gt;Changes the state to &amp;#39;running&amp;#39;.&lt;/em&gt; &lt;/li&gt;        &lt;li&gt;&lt;em&gt;Initializes the parameters (including this) of the iterator block to the argument values and instance value saved when the enumerator object was initialized.&lt;/em&gt; &lt;/li&gt;        &lt;li&gt;&lt;em&gt;&lt;font color="#ff0000"&gt;Executes the iterator block from the beginning until execution is interrupted (as described below).&lt;/font&gt;&lt;/em&gt; &lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;em&gt;(...)&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;The red line is what&amp;#39;s of interest to us, and you should read it in reverse:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;The code from the beginning of the iterator block till the place where execution is interrupted (i.e. a yield occurs) is executed by MoveNext when transitioning from &amp;#39;before&amp;#39; to &amp;#39;running&amp;#39;.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What if that code contains exception throwing statements?&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &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;if &lt;/font&gt;(first == &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; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;first&amp;quot;&lt;/font&gt;);         &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;/p&gt;   &lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(second == &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; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;second&amp;quot;&lt;/font&gt;);       &lt;br /&gt;&lt;/font&gt;    &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie1 = first.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie2 = second.GetEnumerator(); &lt;/font&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(ie1.MoveNext() &amp;amp;&amp;amp; ie2.MoveNext())         &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;yield return &lt;/font&gt;func(ie1.Current, ie2.Current);         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As you can guess, this code won&amp;#39;t get executed till the very first passage through the iterator&amp;#39;s enumerator object&amp;#39;s MoveNext method. Recall what foreach corresponds to:&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="#008080"&gt;V&lt;/font&gt; v &lt;font color="#0000ff"&gt;in &lt;/font&gt;x) &lt;em&gt;embedded-statement&lt;/em&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;becomes (with C the collection type, E the enumerator type, V the local variable type and T the element type)&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;E&lt;/font&gt; e = ((&lt;font color="#008080"&gt;C&lt;/font&gt;)(x)).GetEnumerator();         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;try&lt;/font&gt; {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;V &lt;/font&gt;v;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(&lt;font color="#ff0000"&gt;e.MoveNext()&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; v = (&lt;font color="#008080"&gt;V&lt;/font&gt;)(&lt;font color="#008080"&gt;T&lt;/font&gt;)e.Current;         &lt;br /&gt;&lt;em&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; embedded-statement&lt;/em&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; }         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;finally &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; }         &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So just calling the iterator does nothing that can cause the exceptions to be thrown, until a call is made to MoveNext, e.g. by using a foreach loop. As we want the exception to be thrown straight away when calling Zip with invalid arguments, the right way to implement our Zip method is:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static class&lt;/font&gt; &lt;font color="#008080"&gt;Enumerable&lt;/font&gt;         &lt;br /&gt;{         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)         &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;if &lt;/font&gt;(first == &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; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;first&amp;quot;&lt;/font&gt;);         &lt;br /&gt;        &lt;br /&gt;&lt;/font&gt;&lt;/p&gt;   &lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;if &lt;/font&gt;(second == &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; &lt;font color="#0000ff"&gt;throw new &lt;/font&gt;&lt;font color="#008080"&gt;ArgumentNullException&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;second&amp;quot;&lt;/font&gt;);       &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;return&lt;/font&gt; ZipInternal(first, second, func);       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160;&amp;#160; private static &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TResult&amp;gt; ZipInternal&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;font color="#0000ff"&gt;this &lt;/font&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TFirst&amp;gt; first, &lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;TSecond&amp;gt; second, &lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; func)       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; {&lt;/font&gt;     &lt;br /&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie1 = first.GetEnumerator();       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;var&lt;/font&gt; ie2 = second.GetEnumerator(); &lt;/font&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while &lt;/font&gt;(ie1.MoveNext() &amp;amp;&amp;amp; ie2.MoveNext())         &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;yield return &lt;/font&gt;func(ie1.Current, ie2.Current);         &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;Conclusion&lt;/h1&gt;  &lt;p&gt;The addition of Zip to LINQ is a nice one, but not a mind-blower. So I hope you&amp;#39;ll accept my apologies for using this as a lame excuse to nag about the implementation of iterators and their subtle impact on exceptions. Next time: generics co- and contra-variance in C# 4.0.&lt;/p&gt;&lt;img src="http://blog.bartdesmet.net/aggbug.aspx?PostID=14055" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>C# 4.0 Feature Focus - Part 2 - Named parameters</title><link>http://blog.bartdesmet.net/blogs/bart/archive/2008/11/01/c-4-0-feature-focus-part-2-named-parameters.aspx</link><pubDate>Sun, 02 Nov 2008 05:58:53 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14038</guid><dc:creator>bart</dc:creator><slash:comments>157</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14038</wfw:commentRss><comments>http://blog.bartdesmet.net/blogs/bart/archive/2008/11/01/c-4-0-feature-focus-part-2-named-parameters.aspx#comments</comments><description>&lt;p&gt;In the previous episode of this feature focus series we talked about &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx"&gt;optional parameters&lt;/a&gt;. Today we&amp;#39;ll cover another feature introduced in C# 4.0, named parameters. One of the most applicable places for optional and named parameters is when dealing with COM interop such as interaction with the Office automation APIs, but they can also be used as a stand-alone language feature. Just like optional parameters, named parameters are a symmetric feature: you can both consume and declare them.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The syntax&lt;/h1&gt;  &lt;p&gt;Assume the following simple subtraction method is defined:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static int &lt;/font&gt;Subtract(&lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &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;a - b;        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The typical way to call this method is obviously by specifying the parameters in order, like Subtract(5, 3). However, with named parameters it&amp;#39;s possible to write the following:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static void &lt;/font&gt;Main()        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(Subtract(b: 3, a: 5));        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Ultimately this translates into a call to Subtract(5, 3). It&amp;#39;s clear the sample above is not very realistic (but you have to admit it&amp;#39;s simplistic). Typically named parameters are used where optional parameters appear in the target method, but you&amp;#39;re not interested in lots of those:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;static void &lt;/font&gt;Bar(&lt;font color="#0000ff"&gt;int &lt;/font&gt;a = 1, &lt;font color="#0000ff"&gt;string &lt;/font&gt;b = &lt;font color="#0000ff"&gt;null&lt;/font&gt;, &lt;font color="#0000ff"&gt;bool &lt;/font&gt;c = &lt;font color="#0000ff"&gt;false&lt;/font&gt;)      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008000"&gt;// ...&lt;/font&gt;      &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;Now assume you&amp;#39;re only interested in the last parameter, without the named parameter feature you&amp;#39;d have to write Bar(1, null, ...) but now you can go ahead and write:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;Bar(c: &lt;font color="#0000ff"&gt;true&lt;/font&gt;);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You might wonder why the syntax uses a colon (:) instead of an assignment equals character (=). The answer is straightforward: assignments have a value and can be used everywhere a value is expected:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="COurier New"&gt;&lt;font color="#0000ff"&gt;bool &lt;/font&gt;c = &lt;font color="#0000ff"&gt;false&lt;/font&gt;;        &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;Bar(c = &lt;font color="#0000ff"&gt;true&lt;/font&gt;);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This will assign true to the local variable c and feed that value in as the first argument of Bar. So colon is the way to go (and I&amp;#39;m not going to start religious debates about the spacing around the :, I&amp;#39;ll leave that to the C/C++ community as those people are experienced in this kind of discussions, trying to reach an agreement on the totally irrelevant placing for the * character &amp;lt;g&amp;gt;).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The implementation&lt;/h1&gt;  &lt;p&gt;It should be clear that the implementation only affects the call site, not the caller. Here&amp;#39;s how the Main method from above looks like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;.method private hidebysig static void&amp;#160; &lt;/font&gt;Main() &lt;font color="#0000ff"&gt;cil managed&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.entrypoint         &lt;br /&gt;&lt;/font&gt;&lt;font color="#008000"&gt;&amp;#160; // Code size&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; 19 (0x13)&lt;/font&gt;        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.maxstack&amp;#160; &lt;/font&gt;2        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.locals init &lt;/font&gt;(&lt;font color="#0000ff"&gt;int32 &lt;/font&gt;V_0,        &lt;br /&gt;&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;int32 &lt;/font&gt;V_1)        &lt;br /&gt;&amp;#160; IL_0000:&amp;#160; &lt;font color="#0000ff"&gt;nop         &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0001:&amp;#160; &lt;font color="#0000ff"&gt;ldc.i4.3         &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0002:&amp;#160; &lt;font color="#0000ff"&gt;stloc.0&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0003:&amp;#160; &lt;font color="#0000ff"&gt;ldc.i4.5         &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0004:&amp;#160; &lt;font color="#0000ff"&gt;stloc.1&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0005:&amp;#160; &lt;font color="#0000ff"&gt;ldloc.1         &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0006:&amp;#160; &lt;font color="#0000ff"&gt;ldloc.0&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0007:&amp;#160; &lt;font color="#0000ff"&gt;call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; int32 &lt;/font&gt;Program::Subtract(&lt;font color="#0000ff"&gt;int32&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;&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;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;int32&lt;/font&gt;)        &lt;br /&gt;&amp;#160; IL_000c:&amp;#160; &lt;font color="#0000ff"&gt;call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; void &lt;/font&gt;[mscorlib]System.Console::WriteLine(&lt;font color="#0000ff"&gt;int32&lt;/font&gt;)        &lt;br /&gt;&amp;#160; IL_0011:&amp;#160; &lt;font color="#0000ff"&gt;nop&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0012:&amp;#160; &lt;font color="#0000ff"&gt;ret&lt;/font&gt;        &lt;br /&gt;}&lt;font color="#008000"&gt; // end of method Program::Main&lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;First of all, notice the names of parameters don&amp;#39;t appear in the call site in any way (they never have, that&amp;#39;s not the way IL works). Ultimately we simply call Subtract with the parameters supplied in the right order. But how we get there is important to take a closer look at:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&amp;#160; IL_0001:&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;ldc.i4.3       &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0002:&amp;#160; &lt;font color="#0000ff"&gt;stloc.0&lt;/font&gt;      &lt;br /&gt;&amp;#160; IL_0003:&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;ldc.i4.5       &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0004:&amp;#160; &lt;font color="#0000ff"&gt;stloc.1&lt;/font&gt;      &lt;br /&gt;&amp;#160; IL_0005:&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;ldloc.1       &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0006:&amp;#160; &lt;font color="#0000ff"&gt;ldloc.0&lt;/font&gt;&lt;/font&gt;    &lt;br /&gt;&lt;/blockquote&gt;  &lt;p&gt;The thing to notice here are the mirrored stloc (store to local variable) versus ldloc (load from local variable) instructions. On lines IL_0002 and IL_0004 values are stored to variables 0 and 1, while on lines IL_0005 and IL_0006 they&amp;#39;re read out in reverse order. What&amp;#39;s happening here is that arguments to the method call are evaluated in lexical order, something that boils down to a one-liner in section 14.4.1 of the C# specification (ECMA-334):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;&lt;strong&gt;14.4.1&amp;#160;&amp;#160;&amp;#160; Argument lists         &lt;br /&gt;&lt;/strong&gt;...        &lt;br /&gt;The expressions of an argument list are always evaluated in the order they are written. &lt;/em&gt;&lt;/p&gt;   &lt;em&gt;[Example: Thus, the example &lt;/em&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#008080"&gt;Test &lt;/font&gt;        &lt;br /&gt;{         &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;F(&lt;font color="#0000ff"&gt;int &lt;/font&gt;x, &lt;font color="#0000ff"&gt;int &lt;/font&gt;y, &lt;font color="#0000ff"&gt;int &lt;/font&gt;z) {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; System.&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;&amp;quot;x = {0}, y = {1}, z = {2}&amp;quot;&lt;/font&gt;, x, y, z);         &lt;br /&gt;&amp;#160; }         &lt;br /&gt;        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;Main() {         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;int &lt;/font&gt;i = 0;         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; F(i++, i++, i++);         &lt;br /&gt;&amp;#160; }         &lt;br /&gt;}        &lt;br /&gt;         &lt;br /&gt;&lt;/font&gt;produces the output       &lt;br /&gt;      &lt;br /&gt;x = 0, y = 1, z = 2      &lt;br /&gt;      &lt;br /&gt;&lt;em&gt;end example] &lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This becomes relevant in the context of side-effects but it should be clear by now that it&amp;#39;s better not to rely on those kind of side-effects at all. Nevertheless, consistency is a must and hence the named parameters invocation syntax follows those rules as well. Here&amp;#39;s the new sample you can predict the output for based on the previous observations:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class&lt;/font&gt; &lt;font color="#008080"&gt;Test &lt;/font&gt;      &lt;br /&gt;{       &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;F(&lt;font color="#0000ff"&gt;int &lt;/font&gt;x, &lt;font color="#0000ff"&gt;int &lt;/font&gt;y, &lt;font color="#0000ff"&gt;int &lt;/font&gt;z) {      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; System.&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#800000"&gt;&amp;quot;x = {0}, y = {1}, z = {2}&amp;quot;&lt;/font&gt;, x, y, z);       &lt;br /&gt;&amp;#160; }       &lt;br /&gt;      &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;Main() {       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;int &lt;/font&gt;i = 0;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; F(z: i++, x: i++, y: i++);       &lt;br /&gt;&amp;#160; }       &lt;br /&gt;}      &lt;br /&gt;&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The caveat&lt;/h1&gt;  &lt;p&gt;This time the caveat is trivial: don&amp;#39;t rename parameters on public methods as they might be used in conjunction with the named parameter feature. Here&amp;#39;s a sample.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Step 1: Compile the following (csc /t:library namedlib.cs)       &lt;br /&gt;&lt;/strong&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;NamedLib&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static int &lt;/font&gt;Subtract(&lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b)        &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;return &lt;/font&gt;a - b;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;Step 2: Compile the following (csc named.cs /r:namedlib.dll)&lt;/strong&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using&lt;/font&gt; System; &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Program&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;static void &lt;/font&gt;Main()        &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="#008080"&gt;Console&lt;/font&gt;.WriteLine(NamedLib.Subtract(b: 3, a: 5));        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;Step 3: Run named.exe&lt;/strong&gt;&lt;/p&gt;    &lt;p&gt;&amp;gt; named.exe     &lt;br /&gt;2&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;Step 4: Change the library and recompile&lt;/strong&gt;&lt;/p&gt;   &lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;NamedLib&lt;/font&gt;      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static int &lt;/font&gt;Subtract(&lt;font color="#0000ff"&gt;int &lt;/font&gt;x, &lt;font color="#0000ff"&gt;int &lt;/font&gt;&lt;u&gt;y&lt;/u&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;return &lt;/font&gt;&lt;u&gt;x&lt;/u&gt; - &lt;u&gt;y&lt;/u&gt;;      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; }      &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Step 5: Recompile the application&lt;/strong&gt;&lt;/p&gt;    &lt;p&gt;&lt;em&gt;named.cs(7,27): error CS1739: The best overload for &amp;#39;Subtract&amp;#39; does not have a parameter named &amp;#39;b&amp;#39;&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Names matter. Obviously reordering parameters of the same type without recompiling consumers is a breaking change too (the types of the parameters in the signature doesn&amp;#39;t change, so the overload is still valid but semantics of the parameters have changed), but that&amp;#39;s unrelated to the use of named parameters.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;Named parameters provide an easy way to omit (&amp;quot;skip over&amp;quot;) optional parameters and are typically used in conjunction with that particular feature. However, they can be used in isolation as well. Once more, library designers should be cautious about messing with the public methods they provide. In particular, &lt;strong&gt;&lt;u&gt;make sure names on publicly exposed methods are stable as changes to those have the potential of breaking callers&lt;/u&gt;&lt;/strong&gt;. Another reason to spend time on XML documenting public members, as you&amp;#39;ll double-check (I hope) the &amp;lt;param /&amp;gt; tag for its name.&lt;/p&gt;  &lt;p&gt;Oh, and did you notice the parallels with concepts in PowerShell on positional and named cmdlet arguments? The only piece missing are aliases ;-).&lt;/p&gt;  &lt;p&gt;Next time, before we dive into more language-specific features, a short intermezzo in LINQ with a new operator: Zip. Enjoy!&lt;/p&gt;&lt;img src="http://blog.bartdesmet.net/aggbug.aspx?PostID=14038" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item><item><title>C# 4.0 Feature Focus - Part 1 - Optional parameters</title><link>http://blog.bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx</link><pubDate>Sat, 01 Nov 2008 04:31:42 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14036</guid><dc:creator>bart</dc:creator><slash:comments>135</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blog.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14036</wfw:commentRss><comments>http://blog.bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx#comments</comments><description>&lt;p&gt;Welcome to the first post in my new C# 4.0 Feature Focus series. Today we&amp;#39;ll start by taking a look at optional parameters, a long-standing request from the community that made it to C# 4.0. By itself, the feature is definitely useful but in conjunction with the mission to make COM interop easier, there&amp;#39;s even more value to it. In this post I&amp;#39;ll outline what the feature looks like, how it&amp;#39;s implemented and what the &lt;u&gt;important caveats&lt;/u&gt; are.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The syntax&lt;/h1&gt;  &lt;p&gt;C# 4.0 can both declare and consume optional parameters. Here&amp;#39;s a sample of a very simple method that declares a parameter as optional:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void &lt;/font&gt;SayHello(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s = &lt;font color="#800000"&gt;&amp;quot;Hello World!&amp;quot;&lt;/font&gt;)        &lt;br /&gt;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(s);        &lt;br /&gt;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This means you can either call Do with one argument or without an argument, in which case the default value is used:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;OptionalDemo&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void &lt;/font&gt;Main()        &lt;br /&gt;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;.SayHello();        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;.SayHello(&lt;font color="#800000"&gt;&amp;quot;Hello Bart!&amp;quot;&lt;/font&gt;);        &lt;br /&gt;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice all optional parameters need to come at the end of the argument list.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;optlib.cs(3,58): error CS1737: Optional parameters must appear after all required parameters&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;If this weren&amp;#39;t the case all sorts of ambiguities would result, e.g.:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static void &lt;/font&gt;SayHello(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s1 = &lt;font color="#800000"&gt;&amp;quot;Hello World!&amp;quot;&lt;/font&gt;, &lt;font color="#0000ff"&gt;string &lt;/font&gt;s2)&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;What would a call with a single string argument result in? Would the parameter be bound to s1, overriding the default, or would it bind to s2?&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The implementation&lt;/h1&gt;  &lt;p&gt;How does it work? Let&amp;#39;s start by taking a look at the definition side. Here&amp;#39;s the IL corresponding to the declaration of SayHello above:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;.method public hidebysig static void&amp;#160; &lt;/font&gt;SayHello([&lt;font color="#0000ff"&gt;&lt;strong&gt;opt&lt;/strong&gt;&lt;/font&gt;] &lt;font color="#0000ff"&gt;string &lt;/font&gt;s) &lt;font color="#0000ff"&gt;cil managed&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;&lt;strong&gt;.param&lt;/strong&gt; &lt;/font&gt;[1] = &lt;font color="#800000"&gt;&amp;quot;Hello World!&amp;quot;&lt;/font&gt;        &lt;br /&gt;&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008000"&gt;// Code size&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; 9 (0x9)         &lt;br /&gt;&lt;/font&gt;&amp;#160; &lt;font color="#0000ff"&gt;.maxstack&amp;#160; &lt;/font&gt;8        &lt;br /&gt;&amp;#160; IL_0000:&amp;#160; &lt;font color="#0000ff"&gt;nop&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0001:&amp;#160; &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;ldarg.0         &lt;br /&gt;&lt;/font&gt;&amp;#160; IL_0002:&amp;#160; &lt;font color="#0000ff"&gt;call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; void &lt;/font&gt;[mscorlib]System.Console::WriteLine(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)        &lt;br /&gt;&amp;#160; IL_0007:&amp;#160; &lt;font color="#0000ff"&gt;nop&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0008:&amp;#160; &lt;font color="#0000ff"&gt;ret&lt;/font&gt;        &lt;br /&gt;} &lt;font color="#008000"&gt;// end of method OptionalDemoLib::SayHello&lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Two things are relevant here. First of all, the parameter is decorated with the [opt]. Second, the method body contains a .param directive. It turns out both of those primitives have been supported in the CLI since the very beginning. Visual Basic is one of the languages that already uses this today. Let&amp;#39;s dive a little deeper using the CLI specification (&lt;a href="http://msdn.microsoft.com/en-us/netframework/aa569283.aspx"&gt;ECMA 335&lt;/a&gt;), partition II:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;15.4&amp;#160;&amp;#160;&amp;#160; Defining methods       &lt;br /&gt;&lt;/strong&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;opt&lt;/font&gt; specifies that this parameter is intended to be optional from an end-user point of view. The value to be supplied is stored using the &lt;font face="Courier New"&gt;.param &lt;/font&gt;syntax ($15.4.1.4).      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;15.4.1&amp;#160;&amp;#160;&amp;#160; Method body       &lt;br /&gt;&lt;/strong&gt;      &lt;br /&gt;| &lt;font face="Courier New"&gt;.param &lt;/font&gt;`[` &lt;em&gt;Int32&lt;/em&gt; `]` [ `=` &lt;em&gt;FieldInit&lt;/em&gt; ]&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Store a constant &lt;em&gt;FieldInit&lt;/em&gt; value for parameter &lt;em&gt;Int32&lt;/em&gt;.      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;15.4.1.4&amp;#160;&amp;#160;&amp;#160; The .param directive&lt;/strong&gt;      &lt;br /&gt;      &lt;br /&gt;This directive stores in the metadata a &lt;u&gt;constant value&lt;/u&gt; associated with method parameter number &lt;em&gt;Int32&lt;/em&gt;, see $22.9. (...) Unlike CIL instructions, .param uses index 0 to specify the return value of the method, index 1 to specify the first parameter of the method, ...      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;22.9&amp;#160;&amp;#160;&amp;#160; Constant : 0x0B&lt;/strong&gt;      &lt;br /&gt;      &lt;br /&gt;The &lt;em&gt;Constant &lt;/em&gt;table is used to store compile-time, constant values for fields, parameters, and properties. The &lt;em&gt;Constant&lt;/em&gt; table has the following columns:      &lt;br /&gt;- &lt;em&gt;Type &lt;/em&gt;...      &lt;br /&gt;- &lt;em&gt;Parent&lt;/em&gt; ...      &lt;br /&gt;- &lt;em&gt;Value&lt;/em&gt; (an index into the Blob heap)      &lt;br /&gt;      &lt;br /&gt;Note that &lt;em&gt;Constant&lt;/em&gt; information odes not directly influence runtime behavior, although it is visible via Reflection. Compilers inspect this information, at compile time, when importing metadata, but &lt;u&gt;the value of the constant itself, if used, becomes embedded into the CIL stream the compiler emits&lt;/u&gt;. There are no CIL instructions to access the &lt;em&gt;Constant&lt;/em&gt; table at runtime.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I&amp;#39;ll come back to the remark in paragraph 22.9 in just a second. An important thing here is that the value needs to be constant, so no new&amp;#39;ing up of stuff or results of methods calls are allowed:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;optlib.cs(3,23): error CS1736: Default parameter value for &amp;#39;s&amp;#39; must be a compile-time constant&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What does the call-site look like if the parameter is omitted?&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;.method private hidebysig static void&amp;#160; &lt;/font&gt;Main() &lt;font color="#0000ff"&gt;cil managed&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.entrypoint&lt;/font&gt;        &lt;br /&gt;&lt;font color="#008000"&gt;&amp;#160; // Code size&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; 24 (0x18)&lt;/font&gt;        &lt;br /&gt;&amp;#160; &lt;font color="#0000ff"&gt;.maxstack&amp;#160; &lt;/font&gt;8        &lt;br /&gt;&amp;#160; IL_0000:&amp;#160; &lt;font color="#0000ff"&gt;nop&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0001:&amp;#160; &lt;font color="#0000ff"&gt;ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font color="#800000"&gt;&amp;quot;Hello World!&amp;quot;&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0006:&amp;#160; &lt;font color="#0000ff"&gt;call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; void &lt;/font&gt;[optlib]OptionalDemoLib::Do(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)        &lt;br /&gt;&amp;#160; IL_000b:&amp;#160; &lt;font color="#0000ff"&gt;nop&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_000c:&amp;#160; &lt;font color="#0000ff"&gt;ldstr&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/font&gt;&lt;font color="#800000"&gt;&amp;quot;Hello Bart!&amp;quot;&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0011:&amp;#160; &lt;font color="#0000ff"&gt;call&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; void &lt;/font&gt;[optlib]OptionalDemoLib::Do(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)        &lt;br /&gt;&amp;#160; IL_0016:&amp;#160; &lt;font color="#0000ff"&gt;nop&lt;/font&gt;        &lt;br /&gt;&amp;#160; IL_0017:&amp;#160; &lt;font color="#0000ff"&gt;ret&lt;/font&gt;        &lt;br /&gt;} &lt;font color="#008000"&gt;// end of method OptionalDemo::Main &lt;/font&gt;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Notice how remark 22.9 applies here. At the call-site both calls look like a call with one argument. The optional argument is &amp;quot;compiled away&amp;quot; on the side of the caller.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The caveat&lt;/h1&gt;  &lt;p&gt;The remark above quoting the CLI specification is a very important one:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;Note that Constant information odes not directly influence runtime behavior, although it is visible via Reflection. Compilers inspect this information, at compile time, when importing metadata, but &lt;u&gt;the value of the constant itself, if used, becomes embedded into the CIL stream the compiler emits&lt;/u&gt;. There are no CIL instructions to access the Constant table at runtime.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In human words, default values are burned into the call site. The metadata specified by the .param directive is only used to keep the constant value around, but as soon as a method is called and optional parameters are used in that call (as determined by the compiler), that value gets copied literally to the call site where it sticks. Let&amp;#39;s illustrate this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Step 1: Compile the following (csc /t:library optlib.cs)&lt;/strong&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;System;        &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void &lt;/font&gt;SayHello(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s = &lt;font color="#800000"&gt;&amp;quot;Hello World!&amp;quot;&lt;/font&gt;)        &lt;br /&gt;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(s);        &lt;br /&gt;&amp;#160;&amp;#160; }        &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Step 2: Compile the following (csc opt.cs /r:optlib.dll)&lt;/strong&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;System;      &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;System.Reflection;&lt;/font&gt;      &lt;br /&gt;      &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;OptionalDemo&lt;/font&gt;      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void &lt;/font&gt;Main()      &lt;br /&gt;&amp;#160;&amp;#160; {      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;.SayHello();      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;).GetMethod(&lt;font color="#800000"&gt;&amp;quot;SayHello&amp;quot;&lt;/font&gt;).GetParameters()[0].RawDefaultValue);      &lt;br /&gt;&amp;#160;&amp;#160; }      &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;strong&gt;Step 3: Run opt.exe       &lt;br /&gt;&lt;/strong&gt;      &lt;br /&gt;&amp;gt; opt.exe      &lt;br /&gt;Hello World!      &lt;br /&gt;Hello World!      &lt;br /&gt;&lt;/p&gt;    &lt;p&gt;&lt;strong&gt;Step 4: Change the library and recompile (&lt;u&gt;don&amp;#39;t&lt;/u&gt; recompile the opt.cs demo caller)        &lt;br /&gt;&lt;/strong&gt;      &lt;br /&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;System;        &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;        &lt;br /&gt;{        &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void &lt;/font&gt;SayHello(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s = &lt;font color="#800000"&gt;&lt;u&gt;&amp;quot;Hello Universe!&amp;quot;&lt;/u&gt;&lt;/font&gt;)        &lt;br /&gt;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(s);        &lt;br /&gt;&amp;#160;&amp;#160; }        &lt;br /&gt;}        &lt;br /&gt;&lt;/font&gt;      &lt;br /&gt;&lt;strong&gt;Step 5: Run opt.exe       &lt;br /&gt;&lt;/strong&gt;      &lt;br /&gt;&amp;gt; opt.exe      &lt;br /&gt;&lt;font color="#ff0000"&gt;Hello World!       &lt;br /&gt;&lt;/font&gt;Hello Universe!&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In step 2 we&amp;#39;re introducing the use of reflection to get the default value for the optional parameter. This is run-time reflection that actually inspects the metadata associated with the method&amp;#39;s parameter. However, as 22.9 mentions: &amp;quot;There are no CIL instructions to access the &lt;em&gt;Constant&lt;/em&gt; table at runtime.&amp;quot;, so the default value gets &lt;font color="#ff0000"&gt;burned &lt;/font&gt;into the call site by the compiler. This is no different than the same constant-ness encountered in &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2006/04/04/3867.aspx"&gt;the difference between readonly variables and constants&lt;/a&gt;. The key take-away from this: once you expose a default parameter value on a public method, you can never change it without recompiling all clients that depend on it. For library writers, this never means &lt;em&gt;never ever&lt;/em&gt;. If you need the flexibility of changing defaults afterwards, consider providing overloads instead:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;System;      &lt;br /&gt;      &lt;br /&gt;&lt;font color="#0000ff"&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void &lt;/font&gt;SayHello()      &lt;br /&gt;&amp;#160;&amp;#160; {      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; SayHello(&lt;font color="#800000"&gt;&amp;quot;Hello Universe!&amp;quot;&lt;/font&gt;);      &lt;br /&gt;&amp;#160;&amp;#160; }      &lt;br /&gt;      &lt;br /&gt;&lt;font color="#0000ff"&gt;&amp;#160;&amp;#160; public static void &lt;/font&gt;SayHello(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s)      &lt;br /&gt;&amp;#160;&amp;#160; {      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(s);      &lt;br /&gt;&amp;#160;&amp;#160; }      &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;This way the constant remains on the definition side and can be changed over there at will. Not that you should do so regularly of course, as you&amp;#39;re after all changing defaults that are hopefully documented somewhere in the XML comments for your public methods. Yet another way to attack the problem if you have a bunch of parameters is to take in a property &amp;quot;bag&amp;quot; as the argument to the method (in practice and object with properties for all the supported setting &amp;quot;parameters&amp;quot;). That way every value can be optional and the method can examine whether certain omissions can be granted. Dispatching to the internal implementation with the maximum parameter list could use techniques like null-coalescing (??):&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;public static void &lt;/font&gt;ComplexSayHello(&lt;font color="#008080"&gt;Message&lt;/font&gt;&lt;font color="#000000"&gt; arg)&lt;/font&gt;      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160; ComplexSayHelloInternal(..., arg.Text ?? &lt;font color="#800000"&gt;&amp;quot;Hello Universe!&amp;quot;&lt;/font&gt;, ...);      &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;Use the right approach - all techniques have their benefits.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The past&lt;/h1&gt;  &lt;p&gt;We&amp;#39;ve talked about the future, but let me point out it was actually possible to &lt;em&gt;declare&lt;/em&gt; optional parameters in C# before, using parameter metadata custom attributes:&lt;/p&gt;  &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;System;      &lt;br /&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;using &lt;/font&gt;System.Runtime.InteropServices;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;       &lt;br /&gt;        &lt;br /&gt;public static class &lt;/font&gt;&lt;font color="#008080"&gt;OptionalDemoLib&lt;/font&gt;      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public static void &lt;/font&gt;SayHello([&lt;font color="#008080"&gt;Optional&lt;/font&gt;][&lt;font color="#008080"&gt;DefaultParameterValue&lt;/font&gt;(&lt;font color="#800000"&gt;&amp;quot;Hello Universe!&amp;quot;&lt;/font&gt;)] &lt;font color="#0000ff"&gt;string &lt;/font&gt;s)      &lt;br /&gt;&amp;#160;&amp;#160; {      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(s);      &lt;br /&gt;&amp;#160;&amp;#160; }      &lt;br /&gt;}&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;This produces the same IL as the sample shown earlier using C# 4.0 syntax. C# couldn&amp;#39;t consume this method though without specifying all parameters, but now it can.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;Optional parameters are a beautiful feature and will make life easier when dealing with old COM-driven libraries that were designed with this language feature in mind (amongst others such as named parameters, see next post). To keep the picture symmetric, C# 4.0 also provides the ability to define optional parameters, but be well-aware of the call site burning fact mentioned above. &lt;strong&gt;&lt;u&gt;Only use optional parameters if the optional value is really constant in the time dimension&lt;/u&gt;&lt;/strong&gt; unless you&amp;#39;re never going to expose the optional value to the outside world (but it&amp;#39;s damn easy to make a previously internal or private method public and forgetting about this fact, so the first rule should be the strongest decisive factor...). Don&amp;#39;t get me wrong: I like the feature a lot, but powerful weapons need safety warnings.&lt;/p&gt;  &lt;p&gt;Next time: named parameters. Enjoy!&lt;/p&gt;&lt;img src="http://blog.bartdesmet.net/aggbug.aspx?PostID=14036" width="1" height="1"&gt;</description><category domain="http://blog.bartdesmet.net/blogs/bart/archive/tags/C_2300_+4.0/default.aspx">C# 4.0</category></item></channel></rss>