<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://community.bartdesmet.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>B# .NET Blog</title><link>http://community.bartdesmet.net/blogs/bart/default.aspx</link><description>Bart De Smet&amp;#39;s on-line blog (0x2B | ~0x2B, that&amp;#39;s the question)</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 2</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/27/to-bind-or-not-to-bind-dynamic-expression-trees-part-2.aspx</link><pubDate>Wed, 27 Aug 2008 23:05:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13917</guid><dc:creator>bart</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13917</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/27/to-bind-or-not-to-bind-dynamic-expression-trees-part-2.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;Welcome back to the dynamic expression tree fun. Last time we designed our simplified expression tree class library we’ll be using to enable dynamic treatment of objects. Today, we’ll take this one step further by emitting IL code that resolves the operations invoked on such dynamic objects &lt;u&gt;at runtime&lt;/u&gt; through a mechanism called binders. Before we dive in, let me point out that everything discussed in this series is greatly simplified just to illustrate the core ideas and base mechanisms/principles that make dynamic language stuff work.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Introducing IL generation&lt;/h1&gt;  &lt;p&gt;Dynamic code compilation is a wonderful thing. It’s not that hard once you get the basics right (and have some level of IL opcode understanding) but quite hard to debug. Luckily we have tools like &lt;a href="http://blogs.msdn.com/haibo_luo/archive/2008/03/07/8107924.aspx"&gt;Haibo Luo’s IL Visualizer&lt;/a&gt;. Since I’ll be using this, download it, extract the ZIP file, compile the whole solution and copy ILMonitor\bin\Debug\*.dll to %programfiles%\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers. Alternatively you can put it in your personal Visual Studio 2008\Visualizers folder.&lt;/p&gt;  &lt;p&gt;So, what’s our task? Assume we have the following piece of sample code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Program
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args)
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;o = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;o&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;call = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Call(o, &lt;span style="color:#a31515;"&gt;&amp;quot;Substring&amp;quot;&lt;/span&gt;, a, b);
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;func = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(call, o, a, b);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func);
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(func.&lt;strong&gt;&lt;u&gt;Compile()&lt;/u&gt;&lt;/strong&gt;.DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 1, 2));
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;We already know how to construct the objects and to represent it as a string (which would be (o, a, b) =&amp;gt; o.Substring(a, b)). Now we need to focus on the marked Compile method on LambdaDynamicExpression. Starting with the signature of the delegate, we want to create (at runtime) a method that takes in three “dynamic” parameters (corresponding to parameter expressions o, a and b), returning a resulting object. Since we don’t have any type information available, everything should be System.Object, so we’d end up with the following delegate:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#0000ff"&gt;delegate object &lt;/font&gt;&lt;font color="#008080"&gt;TheDynamicLambdaFunction&lt;/font&gt;(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o, &lt;font color="#0000ff"&gt;object &lt;/font&gt;a, &lt;font color="#0000ff"&gt;object &lt;/font&gt;b);&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Looking at Compile as a black box, it will return an instance of this delegate pointing at an on-the-fly generated method corresponding to the lambda’s body expression. Returning a System.Delegate, one can call DynamicInvoke (or cast it to a compatible delegate) to invoke it with the given parameters. Obviously we want the call to do “the right thing”, in the sample above it would correspond to a method call to System.String::Substring on “Bart”, passing in startIndex 1 and length 2, producing another string containing “ar”.&lt;/p&gt;

&lt;p&gt;It should be clear that we need to emit IL on the fly to translate the lambda expression but also the lambda’s body which could be anything, not just a MethodCallDynamicExpression. Since we lack other expression node types, one such (trivial) thing would be:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(&lt;strong&gt;&lt;u&gt;x&lt;/u&gt;&lt;/strong&gt;, x);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;which is just the identity function (the underlined bold ‘o’ above indicates the lamdba’s body). I intentionally named the expression above “I” conform SKI combinators where I is defined as λx . x. Similarly we could define the K combinator as:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;y = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;y&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;K = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(x, x, y);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(K);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(K.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;, 123));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;but we got sidetracked, so time to move on. The whole point here is that we can’t assume the body of the lambda to be a MethodCallDynamicExpression. So, how do we tackle this? An important observation one can make is this: an expression represents a single value. Right, so what? Wait a minute, is IL-code not stack-based? Adding the two things together we could think of the following solution:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Calling a Compile method on an expression tree object, given a writeable stream for IL instructions, should add all the instructions to the stream required to evaluate the expression, leaving the result of the evaluation on top of the stack.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A LambdaDynamicExpression is the only dynamic expression that supports a publicly visible Compile method. It’s pseudo-code would look like:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Create an IL stream; here the IL stack is empty.&lt;/li&gt;

  &lt;li&gt;Take the Body expression and compile it by emitting IL instructions for it; this causes the IL stack to be one high.&lt;/li&gt;

  &lt;li&gt;Add an IL return instruction to return the object on top of the stack.&lt;/li&gt;

  &lt;li&gt;Return a delegate pointing to the method represented by the generated IL code.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Supporting expression compilation&lt;/h1&gt;

&lt;p&gt;To make this work, we’ll first extend the base class by adding one more method:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
/// &lt;/span&gt;&lt;span style="color:green;"&gt;Class representing a dynamic expression tree.
&lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
&lt;/span&gt;&lt;span style="color:blue;"&gt;abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:gray;"&gt;/// &amp;lt;summary&amp;gt;
    /// &lt;/span&gt;&lt;span style="color:green;"&gt;Appends IL instructions to calculate the expression&amp;#39;s runtime value, putting it on top of the evaluation stack.
    &lt;/span&gt;&lt;span style="color:gray;"&gt;/// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;ilgen&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;IL generator to append to.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;ldArgs&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color:green;"&gt;Lambda argument mappings.&lt;/span&gt;&lt;span style="color:gray;"&gt;&amp;lt;/param&amp;gt;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;protected internal abstract void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs);&lt;/pre&gt;

  &lt;pre class="code"&gt;    …&lt;br /&gt;}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This method will take in two things: the IL generator (referred to as “IL stream” in the previous paragraph) and a mapping table for the lambda’s parameter expressions. Why do we need the latter, or better: what does it map the parameter expressions to? Assume we’re compiling&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(o, a, b) =&amp;gt; o.Substring(a, b)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;While traversing the expression tree, asking every node in the correct order to emit IL instructions, we’ll encounter references to the parameters again. Our goal is to write a dynamic method looking like this:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font color="#0000ff"&gt;object &lt;/font&gt;GeneratedDynamicMethod(&lt;font color="#0000ff"&gt;object &lt;/font&gt;o, &lt;font color="#0000ff"&gt;object &lt;/font&gt;a, &lt;font color="#0000ff"&gt;object &lt;/font&gt;b)

    &lt;br /&gt;{

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;return &lt;/font&gt;o.Substring(a, b);

    &lt;br /&gt;}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;where the . obviously denotes a dynamic method call in this case. As we encounter parameter expressions like o, a or b during the translation for the method body, we need to know how to load those parameters from the argument list on the dynamic method. First of all, notice the lambda parameters got mapped in order of specification to correspond to arguments on the generated dynamic method, i.e. o as the first lambda parameter and is the first parameter on the generated method. And so on. This is precisely what the ldArgs argument on Compile stands for: a mapping from the parameter expression representation from the lambda parameters onto the concrete indices for the arguments:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;o –&amp;gt; 0
    &lt;br /&gt;a –&amp;gt; 1

    &lt;br /&gt;b –&amp;gt; 2&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Whenever we encounter such a parameter expression during the compilation, we know the position of the argument, so we can emit a &lt;em&gt;ldarg&lt;/em&gt; instruction. This is the most trivial Compile override:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!ldArgs.ContainsKey(&lt;span style="color:blue;"&gt;this&lt;/span&gt;))
            &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;Parameter expression &amp;quot; &lt;/span&gt;+ Name + &lt;span style="color:#a31515;"&gt;&amp;quot; is not in scope.&amp;quot;&lt;/span&gt;);

        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ldarg, ldArgs[&lt;span style="color:blue;"&gt;this&lt;/span&gt;]);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    …
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This simply says, whenever code needs to be emitted for a ParameterDynamicExpression, simply try to find it in the dictionary to map it onto the formal parameter index on the dynamic method being emitted and turn it into a &lt;em&gt;ldarg &lt;/em&gt;instruction for that argument index. Real full-fledged expression tree implementations would be slightly more complicated because arguments could be hidden when dealing with nested lambdas (quoting, invocation expressions, etc) but that would take us too far away from home.&lt;/p&gt;

&lt;p&gt;For the LambdaDynamicExpression, besides a public Compile method, there will also be an override to the inherited one. It simply asks the Body expression to emit itself (which will result in a one-level high stack containing the evaluation result of the body expression), followed by a ret instruction (simply returning the value evaluated through the Body’s IL code preceding it):&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;Compile(&lt;span style="color:#2b91af;"&gt;ILGenerator &lt;/span&gt;ilgen, &lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; ldArgs)
    {
        Body.Compile(ilgen, ldArgs);
        ilgen.Emit(&lt;span style="color:#2b91af;"&gt;OpCodes&lt;/span&gt;.Ret);
    }&lt;/pre&gt;

&lt;pre class="code"&gt;    …&lt;br /&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Emitting code&lt;/h1&gt;

&lt;p&gt;For this post, we’ll omit an implementation for MethodCallDynamicExpression as that will be part of the next post focusing on binders. All we want to get to work today is the I combinator or identity function (yeah, another world-beater :-)):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;x = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Parameter(&lt;span style="color:#a31515;"&gt;&amp;quot;x&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;I = &lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;.Lambda(x, x);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(I.Compile().DynamicInvoke(&lt;span style="color:#a31515;"&gt;&amp;quot;Bart&amp;quot;&lt;/span&gt;));&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;In other words, today we’ll focus on the plumbing of emitting the code and wrapping the method in a delegate that can be returned upon calling LambdaDynamicExpression.Compile. The result for the sample above would be equivalent to:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
{
    &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;(&lt;u&gt;&lt;span style="color:blue;"&gt;delegate&lt;/span&gt;(&lt;span style="color:blue;"&gt;object &lt;/span&gt;x) { &lt;span style="color:blue;"&gt;return &lt;/span&gt;x; }&lt;/u&gt;);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The underlined portion is the code corresponding to I’s compilation. In IL-terms it would be as simplistic as this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;ldarg.0
    &lt;br /&gt;ret&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This emitted IL method body then needs to get the signature that says “taking in an object, returning an object”. All of this makes up the &lt;em&gt;dynamic method&lt;/em&gt;. But we’re not done yet, as we need to return a delegate to it. In the free translation above, I’ve leveraged the generic System.Func&amp;lt;T1,R&amp;gt; delegate but we only have a limited number of those (up to four arguments), so what if we encounter a method that takes more arguments? Indeed, we’ll need to generate our own delegate types as well. Notice we could cache those very efficiently: the ones with arity (~ number of parameters) up to 4 could simply be mapped onto System.Func delegates with System.Object type parameters, while others would be generated on the fly and kept for reuse if another method with same arity gets compiled. We’ll omit this optimization for now.&lt;/p&gt;

&lt;p&gt;Here’s how the code to create our own delegate type looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;private static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;GetDynamicDelegate(&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] argumentTypes, &lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;returnType)
{
    &lt;span style="color:green;"&gt;//
    // Assemblies contain modules; generate those with unique names.
    // The generated assembly is runtime only (doesn&amp;#39;t need to be saved to disk).
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AssemblyBuilder &lt;/span&gt;assemblyBuilder = &lt;span style="color:#2b91af;"&gt;AppDomain&lt;/span&gt;.CurrentDomain.DefineDynamicAssembly(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;AssemblyName&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Guid&lt;/span&gt;.NewGuid().ToString()), &lt;span style="color:#2b91af;"&gt;AssemblyBuilderAccess&lt;/span&gt;.Run);
    &lt;span style="color:#2b91af;"&gt;ModuleBuilder &lt;/span&gt;moduleBuilder = assemblyBuilder.DefineDynamicModule(&lt;span style="color:#2b91af;"&gt;Guid&lt;/span&gt;.NewGuid().ToString());

    &lt;span style="color:green;"&gt;//
    // Our delegate is a private sealed type deriving from MultiCastDelegate.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;TypeBuilder &lt;/span&gt;typeBuilder = moduleBuilder.DefineType(&lt;span style="color:#a31515;"&gt;&amp;quot;Lambdas&amp;quot;&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.NotPublic | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.Sealed | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.AutoLayout | &lt;span style="color:#2b91af;"&gt;TypeAttributes&lt;/span&gt;.AnsiClass, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;MulticastDelegate&lt;/span&gt;));

    &lt;span style="color:green;"&gt;//
    // The delegate&amp;#39;s constructor is a &amp;quot;special name&amp;quot; method with signature (object native int).
    // It doesn&amp;#39;t have a method body by itself; rather, it&amp;#39;s supplied by the managed runtime.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ConstructorBuilder &lt;/span&gt;ctorBuilder = typeBuilder.DefineConstructor(&lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.HideBySig | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.SpecialName | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.RTSpecialName, &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.Standard, &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[] { &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;IntPtr&lt;/span&gt;) });
    ctorBuilder.SetImplementationFlags(&lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Runtime | &lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Managed);

    &lt;span style="color:green;"&gt;//
    // We only need the Invoke method (BeginInvoke and EndInvoke are irrelevant for us).
    // It doesn&amp;#39;t have a method body by itself; rather, it&amp;#39;s supplied by the managed runtime.
    // Here our delegate signature is enforced.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodBuilder &lt;/span&gt;invokeMethodBuilder = typeBuilder.DefineMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;Invoke&amp;quot;&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Public | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.NewSlot | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.HideBySig | &lt;span style="color:#2b91af;"&gt;MethodAttributes&lt;/span&gt;.Virtual, &lt;span style="color:#2b91af;"&gt;CallingConventions&lt;/span&gt;.HasThis, returnType, argumentTypes);
    invokeMethodBuilder.SetImplementationFlags(&lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Runtime | &lt;span style="color:#2b91af;"&gt;MethodImplAttributes&lt;/span&gt;.Managed);

    &lt;span style="color:green;"&gt;//
    // Return the created delegate type.
    // Notice we could cache this for reuse by other dynamic methods.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;typeBuilder.CreateType();
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Lots of attribute flags which you can read all about in the CLI specification. I don’t pretend to memorize all of those attributes; why would I if ILDASM makes life just great? :-)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="260" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb.png" width="631" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the screenshot of ILDASM showing a delegate for a method with signature object(object, object) as you can see on the Invoke method. We don’t need any of the asynchronous pattern implementation, so we just need a constructor and Invoke method (see section IIA.13.6 on “Delegates” in the CLI standard). One special thing about those is they don’t have an IL code body as they are “runtime managed” (see IIA.14.4.3 on “Implementation Attributes of Methods” in the CLI standard):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_3.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="166" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_3.png" width="640" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that we can generate the delegate, we just need to ask the lambda (since that’s the root) expression tree to emit its IL code, which will traverse the entire tree. In order to be able to do this, we need to keep mapping information about the lambda parameters mapped onto the formal arguments as mentioned earlier. Here’s the result:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
{
    &lt;span style="color:green;"&gt;//
    // Map the lambda parameters onto formal argument indices.
    // Also build up the argument type array.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;args = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type&lt;/span&gt;[Parameters.Count];
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;ldArgs = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;();
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; args.Length; i++)
    {
        args[i] = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;);
        ldArgs[Parameters[i]] = i;
    }

    &lt;span style="color:green;"&gt;//
    // Compile the expression tree to an IL method body.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;method = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicMethod&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;&amp;quot;&lt;/span&gt;, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;), args);
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;ilgen = method.GetILGenerator();
    Compile(ilgen, ldArgs);

    &lt;span style="color:green;"&gt;//
    // Get the delegate matching the dynamic method signature.
    //
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Type &lt;/span&gt;dynamicDelegate = GetDynamicDelegate(args, &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:blue;"&gt;object&lt;/span&gt;));

    &lt;span style="color:green;"&gt;//
    // Return a delegate pointing at our dynamic method.
    //
    &lt;/span&gt;&lt;span style="color:blue;"&gt;return &lt;/span&gt;method.CreateDelegate(dynamicDelegate);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This code should be relatively straightforward. First we create the mapping while building up an array just containing typeof(object)’s (since all arguments are objects in our dynamic world). Next we create a dynamic method with the right signature, produce the IL generator and let the expression compilation do all of the work to emit the IL. And finally we stick the whole thing in a dynamically created delegate that matches the signature, returning that to the caller. Setting a breakpoint on the last line and executing for the “I” identity combinator shows this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_4.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="184" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_4.png" width="560" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is the IL visualizer we installed earlier. Notice the friendly string representation for the dynamic method shows the signature, which matches the one of the dynamic lambda in the watch window (which is just “I”). Bringing up the IL visualizer shows stunningly complex code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_5.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="133" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_5.png" width="305" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ignore the NOPs inserted by the IL generator, but IL_0000 was emitted by ParameterDynamicExpression.Compile through the compilation of the lambda body. IL_0006 was emitted subsequently by LambdaDynamicExpression.Compile and the stack is nicely in balance. Sure enough, the result printed is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_6.png"&gt;&lt;img title="image" style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="119" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_12A2D/image_thumb_6.png" width="372" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Woohoo – truly dynamic (though simplistic) execution! Next time: method call expressions and binders.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13917" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 1</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-1.aspx</link><pubDate>Wed, 27 Aug 2008 05:40:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13913</guid><dc:creator>bart</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13913</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-1.aspx#comments</comments><description>&lt;p&gt;In the previous post, I outlined the use of the expression trees from the System.Linq.Expressions namespace. Let’s recap to set the scene:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt; data = (&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt; &lt;/font&gt;s, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt; &lt;/font&gt;a, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt; &lt;/font&gt;b) =&amp;gt; s.Substring(a, b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;produces (deep breadth)&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“s”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“a”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;)&lt;/u&gt;, &lt;font color="#800000"&gt;“b”&lt;/font&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt; data = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt;&amp;gt;(       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;u&gt;&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;)&lt;/u&gt;.GetMethod(&lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, &lt;u&gt;&lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Type&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;), &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;) }&lt;/u&gt;), a, b),         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b         &lt;br /&gt;);         &lt;br /&gt;        &lt;br /&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;int&lt;/u&gt;&lt;/font&gt;, &lt;font color="#0000ff"&gt;&lt;u&gt;string&lt;/u&gt;&lt;/font&gt;&amp;gt; fun = data.Compile();         &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where I’ve indicated all the strong typing using underlines. Wow, that’s a lot dude! Based on all of this strong typing, there are little or no runtime surprises possible concerning running the right method (unless a MissingMethodException occurs for some reason). Obviously, expression trees could be much more complex but to illustrate the core points of the type system, we’ll restrict ourselves to parameters, method calls and lambdas.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;So what do we want to try now? We want to design an API similar to the one used above but without all this type information. Essentially, it would look like:&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“s”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“a”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“b”&lt;/font&gt;);     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008080"&gt;LambdaExpression&lt;/font&gt; data = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, a, b),       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b       &lt;br /&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Delegate&lt;/font&gt; fun = data.Compile();       &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun.&lt;u&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;Invoke&lt;/u&gt;(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;and all of a sudden we see the dynamic aspect lurking around the corner on the very last line where we call through the weakly-typed delegate passing in three &lt;em&gt;objects&lt;/em&gt; which just happen to be a string and two ints, causing the lookup for a Substring method applied to s (becoming “Bart”) with arguments a and b (respectively 1 and 2) to succeed. The important thing here though is that a “Substring” method with a compatible signature might be available on another type, maybe type Bar, but taking in two longs:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;class &lt;/font&gt;&lt;font color="#008080"&gt;Bar&lt;/font&gt;       &lt;br /&gt;{       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;public &lt;/font&gt;&lt;font color="#008080"&gt;Foo &lt;/font&gt;Substring(&lt;font color="#0000ff"&gt;long &lt;/font&gt;a, &lt;font color="#0000ff"&gt;long &lt;/font&gt;b) { … }       &lt;br /&gt;}&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The calling code would still work and the console would print the result of Foo.ToString on the instance returned by Bar.Substring. What it takes to make this work consists of three things:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Dynamic expression trees (i.e. as the one above with stripped type information); &lt;/li&gt;    &lt;li&gt;IL code generation at runtime on the fly (to produce the delegate “fun” in the sample above) &lt;/li&gt;    &lt;li&gt;Binders (things that provide runtime support to resolve method calls) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Of course you could go much further than this with complete ASTs (the big brothers to expression trees) and “rules” but we’re not going to reinvent the DLR :-). &lt;a href="http://blogs.msdn.com/mmaly"&gt;Martin Maly&lt;/a&gt; has quite some information on those topics on his blog (must-reads!). Today we’ll cover the first bullet point.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Our dynamic expression trees&lt;/h1&gt;  &lt;p&gt;To disambiguate with the LINQ expression trees, let’s sneak the word Dynamic in, making our sample look like:&lt;/p&gt;  &lt;blockquote&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“s”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“a”&lt;/font&gt;);     &lt;br /&gt;&lt;font color="#008080"&gt;ParameterDynamicExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Parameter(&lt;font color="#800000"&gt;“b”&lt;/font&gt;);     &lt;br /&gt;    &lt;br /&gt;&lt;font color="#008080"&gt;LambdaDynamicExpression&lt;/font&gt; data = &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;.Lambda(     &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;DynamicExpression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, a, b),       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b       &lt;br /&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Delegate&lt;/font&gt; fun = data.Compile();       &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(fun.&lt;u&gt;&lt;strong&gt;Dynamic&lt;/strong&gt;Invoke&lt;/u&gt;(&lt;font color="#800000"&gt;“Bart”&lt;/font&gt;, 1, 2));&lt;/font&gt;&lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;All of those *DynamicExpression classes extend the DynamicExpression base class while having a factory method on DynamicExpression too, following the design of LINQ’s expression trees. We’ll omit the NodeType property for simplicity and the Type property, because we obviously don’t want a static type to be associated with each expression tree node. We’ll also get rid of a lot of node types, just leaving the factories in for our three node types:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_E57/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="369" alt="image" src="http://www.bartdesmet.info/images_wlw/ToBindorNotToBindDynamicExpressionTreesP_E57/image_thumb.png" width="595" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;So, how does this look like? The factory methods will be just convenient syntax around internal constructor calls producing the concrete node types. In addition, we’ll override ToString to produce a friendly-on-the-eye string representation of expression trees, much like our static LINQ friends. First, the DynamicExpression base class:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;Parameter(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;(name);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression &lt;/span&gt;Call(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;instance, &lt;span style="color:blue;"&gt;string &lt;/span&gt;method, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;[] arguments)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression&lt;/span&gt;(instance, method, arguments);
    }

    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;Lambda(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;body, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;[] parameters)
    {
        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression&lt;/span&gt;(body, parameters);
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;    &lt;/font&gt;protected internal abstract void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb);

&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;&lt;font color="#808080"&gt;&lt;/font&gt;&lt;/span&gt;&lt;span style="color:blue;"&gt;    public override string &lt;/span&gt;ToString()
    {
        &lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;StringBuilder&lt;/span&gt;();
        ToString(sb);
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;sb.ToString();
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;We’ll extend this class a bit more in the next part where we’ll tackle compilation, but let’s move on to each of the three subtypes right now:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;ParameterDynamicExpression(&lt;span style="color:blue;"&gt;string &lt;/span&gt;name)
    {
        Name = name;
    }

    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Name { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

&lt;span style="color:blue;"&gt;    protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        sb.Append(Name);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Nothing surprising here. The expression for a dynamic method call is a slightly bit more complicated :-)…&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;MethodCallDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;MethodCallDynamicExpression(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;instance, &lt;span style="color:blue;"&gt;string &lt;/span&gt;method, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;[] arguments)
    {
        Object = instance;
        Method = method;
        Arguments = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt;(arguments);
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;DynamicExpression&lt;/span&gt;&amp;gt; Arguments { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Object { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public string &lt;/span&gt;Method { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }&lt;/pre&gt;

  &lt;pre class="code"&gt;    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        Object.ToString(sb);
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
        sb.Append(Method);
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = Arguments.Count;
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
        {
            Arguments[i].ToString(sb);
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != n - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }

        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;)&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;I told’ya it was going to be mind-blowing. The core thing to notice though is the composability because of the use of DynamicExpressions as the Object (i.e. the instance where we’ll invoke the method on) and the Arguments collection members. Also notice we don’t support static method calls in here (for which Object would be null – you can envision the right checking in the factory method, omitted for brevity) although it would be perfectly possible to come up with such a thing (think about “global functions” for example, but remember we don’t have a type that tells us where to look for the method – ideally you’d have a mixture of statically and dynamically typed trees interwoven). Oh, and the pretty printing logic in ToString isn’t too complex either…&lt;/p&gt;

&lt;p&gt;Finally, let’s move on to the lambda expression class:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;LambdaDynamicExpression &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;DynamicExpression
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;internal &lt;/span&gt;LambdaDynamicExpression(&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;body, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;[] parameters)
    {
        Body = body;
        Parameters = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;&amp;gt;(parameters);
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;DynamicExpression &lt;/span&gt;Body { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ReadOnlyCollection&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterDynamicExpression&lt;/span&gt;&amp;gt; Parameters { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; &lt;span style="color:blue;"&gt;private set&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Delegate &lt;/span&gt;Compile()
    {
        &lt;span style="color:blue;"&gt;return null&lt;/span&gt;;
    }&lt;/pre&gt;

  &lt;pre class="code"&gt;    &lt;span style="color:blue;"&gt;protected internal override void &lt;/span&gt;ToString(&lt;span style="color:#2b91af;"&gt;StringBuilder &lt;/span&gt;sb)
    {
        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;(&amp;quot;&lt;/span&gt;);

        &lt;span style="color:blue;"&gt;int &lt;/span&gt;n = Parameters.Count;
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; n; i++)
        {
            Parameters[i].ToString(sb);
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(i != n - 1)
                sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;, &amp;quot;&lt;/span&gt;);
        }

        sb.Append(&lt;span style="color:#a31515;"&gt;&amp;quot;) =&amp;gt; &amp;quot;&lt;/span&gt;);
        Body.ToString(sb);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Same deal concerning parameterization based on DynamicExpression instances. I promise you the Compile method will be pretty interesting to say the least, so stay tuned for the next post!&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13913" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Dynamic+languages/default.aspx">Dynamic languages</category></item><item><title>To Bind or Not To Bind – Dynamic Expression Trees – Part 0</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-0.aspx</link><pubDate>Tue, 26 Aug 2008 07:59:04 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13912</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13912</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/26/to-bind-or-not-to-bind-dynamic-expression-trees-part-0.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;By now, most of my blog readers will be familiar with the simple concept of expression trees in C# 3.0 and VB 9.0. A quick recap. What’s the type of the expression below?&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) =&amp;gt; s.Substring(a, b)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Shockingly, you can’t tell. Why? Lambdas have two forms of representation: code (as anonymous methods) or data (as expression trees). One more time:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt; code = (&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) =&amp;gt; s.Substring(a, b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;produces&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt; code = &lt;font color="#0000ff"&gt;delegate &lt;/font&gt;(&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) { &lt;font color="#0000ff"&gt;return &lt;/font&gt;s.Substring(a, b); };&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;where&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt;&amp;gt; data = (&lt;font color="#0000ff"&gt;string &lt;/font&gt;s, &lt;font color="#0000ff"&gt;int &lt;/font&gt;a, &lt;font color="#0000ff"&gt;int &lt;/font&gt;b) =&amp;gt; s.Substring(a, b);&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;produces (deep breadth)&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;s = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;), &lt;font color="#800000"&gt;“s”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;a = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;), &lt;font color="#800000"&gt;“a”&lt;/font&gt;);       &lt;br /&gt;&lt;font color="#008080"&gt;ParameterExpression &lt;/font&gt;b = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Parameter(&lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;), &lt;font color="#800000"&gt;“b”&lt;/font&gt;);       &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt;&amp;gt; data = &lt;font color="#008080"&gt;Expression&lt;/font&gt;.Lambda&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;string&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;int&lt;/font&gt;, &lt;font color="#0000ff"&gt;string&lt;/font&gt;&amp;gt;&amp;gt;(       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Expression&lt;/font&gt;&lt;font color="#000000"&gt;.Call(s, &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;string&lt;/font&gt;).GetMethod(&lt;font color="#800000"&gt;“Substring”&lt;/font&gt;, &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Type&lt;/font&gt;[] { &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;), &lt;font color="#0000ff"&gt;typeof&lt;/font&gt;(&lt;font color="#0000ff"&gt;int&lt;/font&gt;) }), a, b),         &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; s, a, b         &lt;br /&gt;);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;When calling the Compile method on the produced (lambda-expression) data object we’ll get exactly the same IL code &lt;u&gt;but generated at runtime&lt;/u&gt; through the form of a (delegate pointing at a) dynamic(ally generated) method using Reflection.Emit. So far, so good. But what are the characteristics of the expression tree’s generated code? Two things:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;statically typed &lt;/li&gt;    &lt;li&gt;early-bound &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In more human terms, we know &lt;u&gt;at compile time&lt;/u&gt; the type of all the involved expressions – at the entry points (i.e. the leaf levels) we’re passing it in with uttermost detail (see the Parameter factory method’s first argument for instance) but all intermediate nodes in the expression tree have a type too. E.g. the Expression.Call factory call returns a MethodCallExpression whose wrapped method call’s return type is System.String, hence that becomes the type of the node. Talking about method calls, those are bound at compile time too: we know precisely what method to call because of all the type information available about the arguments.&lt;/p&gt;  &lt;p&gt;Isn’t this cool? Sure it is, but what about dynamic languages? Are those able to use this particular form of expression trees? The simple answer is no; well, at least not in a &lt;em&gt;dynamic&lt;/em&gt; way, meaning with dynamic typing (i.e. the type of every node is determined &lt;u&gt;at run time&lt;/u&gt;) and late binding for methods (i.e. we hope to find a suitable method overload at runtime). What can we do about this? Here we’re getting in the realm of DLR stuff and such. This blog series is not about DLR itself though, it’s rather about outlining some crucial concepts of dynamic typing including &lt;strong&gt;“dynamic expression trees”&lt;/strong&gt; emitting &lt;strong&gt;dynamic call sites&lt;/strong&gt; using &lt;strong&gt;binders&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;In the first part coming up soon, we’ll start by investigating how to build dynamic expression trees.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13912" width="1" height="1"&gt;</description></item><item><title>Appropriate use of Local Variable Type Inference</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/23/appropriate-use-of-local-variable-type-inference.aspx</link><pubDate>Sat, 23 Aug 2008 09:04:45 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13900</guid><dc:creator>bart</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13900</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/23/appropriate-use-of-local-variable-type-inference.aspx#comments</comments><description>&lt;p&gt;By now, most – if not all – readers of my blog will be familiar with this C# 3.0 and VB 9.0 feature called Local Variable Type Inference or Implicitly Typed Local Variables. The idea is simple: since the compiler knows (and hence can infer) type information for expressions, also referred to as rvals, there’s no need for the developer to say the type. In most cases it’s a convenience, for example:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;Dictionary&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Customer&lt;/font&gt;, &lt;font color="#008080"&gt;List&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;PhoneNumber&lt;/font&gt;&amp;gt;&amp;gt; phonebook = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Dictionary&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Customer&lt;/font&gt;, &lt;font color="#008080"&gt;List&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;PhoneNumber&lt;/font&gt;&amp;gt;&amp;gt;();&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;That’s literally saying the same thing twice: declare a variable of type &lt;em&gt;mumble-mumble&lt;/em&gt; and assign it a new instance of type &lt;em&gt;mumble-mumble&lt;/em&gt;. Wouldn’t it be nice just to say:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; phonebook = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Dictionary&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Customer&lt;/font&gt;, &lt;font color="#008080"&gt;List&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;PhoneNumber&lt;/font&gt;&amp;gt;&amp;gt;();&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;while it still means exactly the same as the original fragment? That’s what this language feature allows us to do without loosing any of the strong typing. The reason it’s very convenient in the sample above is because of the introduction of arbitrary type construction capabilities due to generics in CLR 2.0. Before this invention, types couldn’t compose arbitrarily big and type names tend to be not too long-winded (namespaces help here too).&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;As convenient as the case above can be, sometimes type inference is a requirement which is introduced by the invention of anonymous types. Typically those are used in projection clauses of LINQ queries although they can be used in separation as well. E.g.:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;font color="#008080"&gt;Process&lt;/font&gt;.GetProcesses() &lt;font color="#0000ff"&gt;select new &lt;/font&gt;{ Name = p.ProcessName, Memory = p.WorkingSet64 };&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;This piece of code gives birth to an anonymous type with two properties Name and Memory (notice the type of those properties is inferred in a similar way from their assigned right-hand side) which is – as the name implies – a type with an unspeakable name. In reality the above produces something like:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#008080"&gt;IEnumerable&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;AnonymousType1&lt;/font&gt;&amp;gt; res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;font color="#008080"&gt;Process&lt;/font&gt;.GetProcesses() &lt;font color="#0000ff"&gt;select new &lt;/font&gt;{ Name = p.ProcessName, Memory = p.WorkingSet64 };&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;where the AnonymousType1 portion is unknown to the developer, so type inference comes to the rescue.&lt;/p&gt;  &lt;p&gt;Alright. But when is it appropriate to use the type inference feature? Here are some personal rules I tend to apply quite strictly:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Do use type inference…&lt;/li&gt;    &lt;ul&gt;     &lt;li&gt;where anonymous types are used – you can’t go without it (unless you want to treat them as System.Object of course and only care about their ToString method or so):       &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;point = &lt;font color="#0000ff"&gt;new &lt;/font&gt;{ X = 10, Y = 5 }; &lt;font color="#008000"&gt;//OK&lt;/font&gt; – what else could you do?        &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;res = &lt;font color="#0000ff"&gt;from &lt;/font&gt;p &lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;font color="#008080"&gt;Process&lt;/font&gt;.GetProcesses() &lt;font color="#0000ff"&gt;select new &lt;/font&gt;{ Name = p.ProcessName, Memory = p.WorkingSet64 }; &lt;font color="#008000"&gt;//OK&lt;/font&gt; – what else could you do?        &lt;br /&gt;&lt;/li&gt;      &lt;li&gt;when the right-hand side explicitly states the type or the type is clearly inferable by humans given the context:       &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; phonebook = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Dictionary&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Customer&lt;/font&gt;, &lt;font color="#008080"&gt;List&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;PhoneNumber&lt;/font&gt;&amp;gt;&amp;gt;(); &lt;font color="#008000"&gt;//OK&lt;/font&gt; – object construction, with generics&lt;font color="#008000"&gt;         &lt;br /&gt;&lt;/font&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;point = &lt;font color="#0000ff"&gt;new &lt;font color="#008080"&gt;Point&lt;/font&gt; &lt;/font&gt;{ X = 10, Y = 5 }; &lt;font color="#008000"&gt;//OK&lt;/font&gt; – object construction&lt;font color="#0000ff"&gt;         &lt;br /&gt;var&lt;/font&gt; customer = (&lt;font color="#008080"&gt;Customer&lt;/font&gt;)someObject; &lt;font color="#008000"&gt;//OK&lt;/font&gt; – cast&lt;font color="#008000"&gt;         &lt;br /&gt;&lt;/font&gt;&lt;font color="#ff0000"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt;&amp;#160;&lt;/font&gt;products = objects.Cast &amp;lt;&lt;font color="#008080"&gt;Product&lt;/font&gt;&amp;gt;(); &lt;font color="#ff8000"&gt;//Debatable &lt;/font&gt;– clearly &lt;em&gt;something&lt;/em&gt; with Product objects, but a List&amp;lt;T&amp;gt;, a T[], an IEnumerable&amp;lt;T&amp;gt;, or …? Also, the type is mentioned quite far to the right, which doesn’t work too well with left-to-right parsing humans        &lt;br /&gt;&lt;/li&gt;   &lt;/ul&gt;    &lt;li&gt;Don’t use type inference…&lt;/li&gt;    &lt;ul&gt;     &lt;li&gt;for assigning constants to variables of built-in types, e.g. what’s the type of the variables below:       &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;i = 0123456789; &lt;font color="#ff0000"&gt;//NOK&lt;/font&gt; – an Int32        &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;l = 9876543210; &lt;font color="#ff0000"&gt;//NOK&lt;/font&gt; – an Int64        &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;name = &lt;font color="#800000"&gt;“Bart”&lt;/font&gt;; &lt;font color="#ff8000"&gt;//Debatable&lt;/font&gt; – what do you gain?        &lt;br /&gt;&lt;/li&gt;      &lt;li&gt;for “smart” type inference in foreach loops (unless you’re faced with a source of anonymous types):       &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;foreach &lt;/font&gt;(&lt;font color="#0000ff"&gt;var &lt;/font&gt;x &lt;font color="#0000ff"&gt;in &lt;/font&gt;xs) &lt;font color="#ff8000"&gt;//Debatable&lt;/font&gt; – depending on meaningful variable names there might be “good” exceptions to the rule        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; ;        &lt;br /&gt;        &lt;br /&gt;Moreover, foreach inserts casts for you if the source sequence is just an IEnumerable (i.e. not “Of T” aka “&amp;lt;T&amp;gt;”), so the best guess with type inference would be System.Object.        &lt;br /&gt;&lt;/li&gt;      &lt;li&gt;when the right-hand side doesn’t clearly indicate the type:       &lt;br /&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; something = someObject.WeirdMethod().AnotherProperty; &lt;font color="#ff0000"&gt;//NOK&lt;/font&gt; – need to know the specific API        &lt;br /&gt;&lt;/li&gt;      &lt;li&gt;if you want to forcefully exercise some abstraction, e.g. because of your development methodology allowing for “planned refactorings” down the road:       &lt;br /&gt;        &lt;br /&gt;&lt;font color="#008080"&gt;IAnimal &lt;/font&gt;animal1 = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Lion&lt;/font&gt;(); &lt;font color="#008000"&gt;//OK&lt;/font&gt;        &lt;br /&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;animal2 = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Giraffe&lt;/font&gt;(); &lt;font color="#ff0000"&gt;//NOK&lt;/font&gt; – will be the most specific type, i.e. Giraffe        &lt;br /&gt;        &lt;br /&gt;This is an interesting one as all of the refactoring support in the IDE will be based on the most specific type and with var, you force it into the most specific type.&lt;/li&gt;   &lt;/ul&gt; &lt;/ul&gt;  &lt;p&gt;Also, it’s important to realize that mechanical changes to variable declarations (for fun?) can yield undesired behavior due to a change in semantics. A few cases pop to mind:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Lambdas don’t play well with type inference. A lambda can either be represented as code or as data (through an expression tree), so without saying what you want, the compiler can’t know. Indeed, not every rhs has a type by itself:     &lt;br /&gt;      &lt;br /&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt; f = () =&amp;gt; 123;      &lt;br /&gt;&lt;font color="#008080"&gt;Expression&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;int&lt;/font&gt;&amp;gt;&amp;gt; e = () =&amp;gt; 123;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Implicit conversion – the long that became an int:     &lt;br /&gt;      &lt;br /&gt;&lt;font color="#0000ff"&gt;checked&lt;/font&gt;      &lt;br /&gt;{      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;long &lt;/font&gt;i = 1; &lt;font color="#008000"&gt;// don’t change to var…&lt;/font&gt;      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;while&lt;/font&gt; (&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;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(i *= 2); &lt;font color="#008000"&gt;// quiz: does i &amp;lt;&amp;lt;= 1 have the same effect?&lt;/font&gt;      &lt;br /&gt;}      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Explicit interface implementations:&lt;/li&gt;    &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args)
{
    &lt;span style="color:#2b91af;"&gt;IBar &lt;/span&gt;b1 = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Bar&lt;/span&gt;();
    b1.Foo();

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;b2 = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Bar&lt;/span&gt;();
    b2.Foo();
}&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;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IBar
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;void &lt;/span&gt;Foo();
}

&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Bar &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;IBar
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public void &lt;/span&gt;Foo()
    {
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Bar.Foo&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color:blue;"&gt;void &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IBar&lt;/span&gt;.Foo()
    {
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;IBar.Foo&amp;quot;&lt;/span&gt;);
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

  &lt;li&gt;Method hiding:&lt;/li&gt;

  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main(&lt;span style="color:blue;"&gt;string&lt;/span&gt;[] args)
{
    &lt;span style="color:#2b91af;"&gt;Foo &lt;/span&gt;f1 = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ExtendedFoo&lt;/span&gt;();
    f1.Bar();

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;f2 = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ExtendedFoo&lt;/span&gt;();
    f2.Bar();
}&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Foo
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public virtual void &lt;/span&gt;Bar()
    {
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Foo.Bar&amp;quot;&lt;/span&gt;);
    }
}

&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ExtendedFoo &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Foo
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public new void &lt;/span&gt;Bar()
    {
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;ExtendedFoo.Bar&amp;quot;&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;/ul&gt;

&lt;p&gt;In the end, as usual, there’s no silver bullet. However, &lt;strong&gt;one should optimize code for reading it&lt;/strong&gt; (write-once, read-many philosophy). When trying to understand programs (at least imperative ones &amp;lt;g&amp;gt;) we already have to do quite some mental “step though” to absorb the implementation specifics with loops, conditions, class hierarchies, etc. We shouldn’t extend this process of mental debugging or reverse engineering with type inference overhead in cases where it’s not immediately apparent what the intended type is. Even though the IDE will tell you the type of an implicitly-typed local when hovering over it, it’s not the kind of thing we want to rely on to decipher every single piece of code. Similarly, IntelliSense is working great for implicitly typed local variables, but that only affects the write-once side of the story.&lt;/p&gt;

&lt;p&gt;After all, every powerful tool imposes a danger when misused. Type inference is no different in this respect.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13900" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/C_2300_+3.0/default.aspx">C# 3.0</category><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/VB+9.0/default.aspx">VB 9.0</category></item><item><title>Curry for dummies (Cont’d) – A happy ending</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/22/curry-for-dummies-cont-d-a-happy-ending.aspx</link><pubDate>Fri, 22 Aug 2008 15:28:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13890</guid><dc:creator>bart</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13890</wfw:commentRss><comments>http://community.bartdesmet.net/blogs/bart/archive/2008/08/22/curry-for-dummies-cont-d-a-happy-ending.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;I didn’t intend to make this a series of posts but that’s the way things go. Based on feedback from readers and additional questions raised, one decides that add that little bit more to it and ultimate you’re writing a sequel. Where have we been on this journey? First, we took a look at the abstract concept of currying in &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/13/curry-for-dummies.aspx"&gt;Curry for dummies&lt;/a&gt;. Next, evaluation strategies were outlined in &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/18/curry-for-dummies-cont-d-a-note-on-purity.aspx"&gt;Curry for dummies cont&amp;#39;d - A note on purity&lt;/a&gt;, outlining that formal substitution relies on assumptions about the expression involved, i.e. they better are side-effect free to be able to employ call-by-name semantics as opposed to – the much embraced in the imperative world – call-by-value semantics. To challenge the readers, I wrote this:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;Readers looking for a challenge are invited to think about how it would be possible to adapt the original (substitution-driven) &lt;/em&gt;&lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/13/curry-for-dummies.aspx"&gt;&lt;em&gt;Curry for dummies&lt;/em&gt;&lt;/a&gt;&lt;em&gt; code to work with call-by-need semantics; in other words, how can a lambda expression be applied (the number of arguments provided is not really relevant in this discussion) with arguments that are lazily (one time at most) evaluated? I&amp;#39;ll post the answer some time soon.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What I’m suggesting here is to implement call-by-need semantics for applying (in formal terms, using beta-reduction) arguments to functions represented as lambdas. To help with the basic plumbing, I provided the Cell&amp;lt;T&amp;gt; class that looks like this:&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;Cell&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;private bool &lt;/span&gt;_assigned;
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; _func;
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;T _value;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;Cell(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; func)
    {
        _func = func;
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;T Value
    {
        &lt;span style="color:blue;"&gt;get
        &lt;/span&gt;{
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!_assigned)
            {
                _value = _func();
                _assigned = &lt;span style="color:blue;"&gt;true&lt;/span&gt;;
            }

            &lt;span style="color:blue;"&gt;return &lt;/span&gt;_value;
        }
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In essence, this class allows us to evaluate a function upon the first call to retrieve its value. For example,&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;val = &lt;font color="#0000ff"&gt;new &lt;/font&gt;&lt;font color="#008080"&gt;Cell&lt;/font&gt;&amp;lt;&lt;font color="#0000ff"&gt;long&lt;/font&gt;&amp;gt;(() =&amp;gt; &lt;font color="#008080"&gt;DateTime&lt;/font&gt;.Now.Ticks);

      &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#008080"&gt;DateTime&lt;/font&gt;.Now.Ticks + &lt;font color="#800000"&gt;&amp;quot; &amp;quot;&lt;/font&gt; + val.Value);

      &lt;br /&gt;&lt;font color="#008080"&gt;Thread&lt;/font&gt;.Sleep(1000);

      &lt;br /&gt;&lt;font color="#008080"&gt;Console&lt;/font&gt;.WriteLine(&lt;font color="#008080"&gt;DateTime&lt;/font&gt;.Now.Ticks + &lt;font color="#800000"&gt;&amp;quot; &amp;quot;&lt;/font&gt; + val.Value);&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To convince you it really doesn’t change its mind after the initial evaluation, look at the following output:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/CurryfordummiesContdAhappyending_13EBC/image.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="56" alt="image" src="http://bartdesmet.info/images_wlw/CurryfordummiesContdAhappyending_13EBC/image_thumb.png" width="310" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The orange is the capture value and is stable. Obviously it’s later than the green one (why? ironically because of call-by-value semantics to String.Concat in the first Console.WriteLine) and earlier than the red one one second later. Anyway, this is our “smart function evaluator” which obviously relies on the fact that the function it captures doesn’t change its mind. The sample above violates this rule but it provides a way to show you it really works.&lt;/p&gt;

&lt;p&gt;Next, let’s take a look at the signature for function application:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&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;LambdaExpression &lt;/span&gt;CallBy____(&lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;func, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] parameters)&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;We want to create three such functions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;CallByValue &lt;/li&gt;

  &lt;li&gt;CallByName &lt;/li&gt;

  &lt;li&gt;CallByNeed &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;all of which will have the same signature. The way the functions work is as follows: given a lambda expression and a set of parameters, we’ll return another lambda expression that calls the original function, possibly having some remaining parameters. A sample:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &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;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &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;b&amp;quot;&lt;/span&gt;);

&lt;span style="color:blue;"&gt;var &lt;/span&gt;add = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(a, b), a, b); &lt;span style="color:green;"&gt;// represents (int a, int b) =&amp;gt; a + b
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;addOne = CallByValue(add, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1));   &lt;span style="color:green;"&gt;// represents (int b) =&amp;gt; 1 + b
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;three = CallByValue(addOne, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2)); &lt;span style="color:green;"&gt;// represents () =&amp;gt; 3&lt;/span&gt;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;If we’d call through the last function, three, without any parameters, we’d get 3. For call-by-value semantics, it would look like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;() =&amp;gt; Invoke(b =&amp;gt; Invoke((a, b) =&amp;gt; (a + b),1,b),2)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;but that will become clearer as we move forward. Time to switch gears and start implementing all of the strategies.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Call-by-value&lt;/h1&gt;

&lt;p&gt;This is the simplest one. We won’t change the function itself (so, no forms of substitution are carried out in the lambda body), rather we’ll call it with the (evaluated) supplied arguments, keeping remaining arguments. Here’s what it looks like:&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;LambdaExpression &lt;/span&gt;CallByValue(&lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;func, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] parameters)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(parameters.Length &amp;gt; func.Parameters.Count)
        &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;Too many parameters specified.&amp;quot;&lt;/span&gt;);

    &lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;[] lambdaParams = func.Parameters.Skip(parameters.Length).ToArray();
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(func, parameters.Concat(lambdaParams)), lambdaParams);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ignoring the validation, we create a new lambda expression with the remaining parameters, and a body that calls the original lambda with the supplied arguments. A sample:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &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;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &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;b&amp;quot;&lt;/span&gt;);

&lt;span style="color:blue;"&gt;var &lt;/span&gt;add = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(a, b), a, b); &lt;span style="color:green;"&gt;// represents (int a, int b) =&amp;gt; a + b
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;addOne = CallByValue(add, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1));   &lt;span style="color:green;"&gt;// represents (int b) =&amp;gt; 1 + b&lt;/span&gt;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The CallByValue call above does the following:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;[] lambdaParams = func.Parameters.Skip(parameters.Length).ToArray();&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;becomes { a, b }.Skip(1).ToArray() = { b }. So, the &lt;em&gt;lambdaParams&lt;/em&gt; variable contains the remaining parameters. Next, it returns a new lambda expression that does the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Invoke(func, parameters.Concat(lambdaParams)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;which is semantically equivalent to func(1, b). To clarify this, the parameters are 1 (which is passed in as &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1)) and b, the remaining parameter(s). More precisely, we keep the number of arguments to call the original lambda the same, but we’ve concretized one of them (i.e. a := 1). This lambda body is now wrapped in a new lambda that only has b as a parameter. In the end it looks like (pseudo-code):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;b =&amp;gt; ((&lt;strong&gt;&lt;u&gt;a&lt;/u&gt;&lt;/strong&gt;, b) =&amp;gt; a + b)(&lt;strong&gt;&lt;u&gt;1&lt;/u&gt;&lt;/strong&gt;, b)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;where the outer b is different from the inner b (they have different scope) and the binding of a with the constant 1 is pointed out. The ToString result of the produced lambda is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;b =&amp;gt; Invoke((a, b) =&amp;gt; (a + b),1,b)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What are the characteristics of this approach?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Arguments are evaluated before calling the function, which means they are evaluated exactly once. &lt;/li&gt;

  &lt;li&gt;As an implication of the previous, arguments that are not used in the body of the function yield redundant evaluations. &lt;/li&gt;

  &lt;li&gt;An argument that evaluates to the “denotational bottom” (e.g. throws an exception or doesn’t terminate) prevents the call from being made (bail out early, but maybe – see previous point – for no real reason). &lt;/li&gt;

  &lt;li&gt;On the positive side, the technique is easy to understand and compatible with lots of languages (e.g. for interop reasons). &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Call-by-name&lt;/h1&gt;

&lt;p&gt;Slightly more complicated but still easy to understand is call-by-value. The idea here is to substitute occurrences of the parameters in the function’s body to create a new function. To put it another way, we don’t wrap the original function but clone it and rewrite it as a new function with fewer arguments. For the same sample:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &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;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &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;b&amp;quot;&lt;/span&gt;);

&lt;span style="color:blue;"&gt;var &lt;/span&gt;add = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(a, b), a, b); &lt;span style="color:green;"&gt;// represents (int a, int b) =&amp;gt; a + b
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;addOne = CallByName(add, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1));   &lt;span style="color:green;"&gt;// represents (int b) =&amp;gt; 1 + b&lt;/span&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;the comments on the right actually point out literally what’s happening. Indeed, a ToString of the resulting lambda looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;b =&amp;gt; 1 + b&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It’s important to realize that the ‘1’ here could be an arbitrary complex expression that’s put in place wherever ‘a’ was found (because of the binding to the parameter). So, if you’d have the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &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;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;twice = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(a, a), a); &lt;span style="color:green;"&gt;// silly way to double things: (int a) =&amp;gt; a + a
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;six = CallByName(twice, &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))); &lt;span style="color:green;"&gt;// calling twice with argument (1 + 2)&lt;/span&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;we’d get, by formal substitution of a in (int a) =&amp;gt; a + a,&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;() =&amp;gt; (1 + 2) + (1 + 2)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;while call by value would evaluate the (1 + 2) first, resulting in:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;() =&amp;gt; 3 + 3&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;How do we implement it? The original &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/13/curry-for-dummies.aspx"&gt;Curry for dummies&lt;/a&gt; post introduces the use of the expression visitor which we inherit from to create an expression tree cloner that replaces parameter occurrences by a given expression like this:&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;CurryVisitor &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;ExpressionVisitor
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;private &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;gt; _parameters;

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;CurryVisitor(&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;gt; parameters)
    {
        _parameters = parameters;
    }

    &lt;span style="color:blue;"&gt;protected override &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;VisitParameter(&lt;span style="color:#2b91af;"&gt;ParameterExpression &lt;/span&gt;p)
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(_parameters.ContainsKey(p))
            &lt;span style="color:blue;"&gt;return &lt;/span&gt;_parameters[p];

        &lt;span style="color:blue;"&gt;return base&lt;/span&gt;.VisitParameter(p);
    }

    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;Clone(&lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;exp)
    {
        &lt;span style="color:blue;"&gt;return base&lt;/span&gt;.Visit(exp);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Using this tool – that we’ll reuse in the call-by-need implementation as well – we can write call-by-name like 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;LambdaExpression &lt;/span&gt;CallByName(&lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;func, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] parameters)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(parameters.Length &amp;gt; func.Parameters.Count)
        &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;Too many parameters specified.&amp;quot;&lt;/span&gt;);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;assignments = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;gt;();

    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; parameters.Length; i++)
    {
        &lt;span style="color:#2b91af;"&gt;ParameterExpression &lt;/span&gt;parameter = func.Parameters[i];
        &lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;value = parameters[i];

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!parameter.Type.IsAssignableFrom(value.Type))
            &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;Incompatible parameter value type for parameter &amp;quot; &lt;/span&gt;+ parameter.Name);

        assignments[parameter] = value;
    }

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;visitor = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;CurryVisitor&lt;/span&gt;(assignments);
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(visitor.Clone(func.Body), func.Parameters.Skip(parameters.Length).ToArray());
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The most important thing here is that we go through all of the specified parameters (in the sample above that’s the expression (1 + 2)), hand-in-hand with the parameter expressions that correspond to it, adding them to a dictionary. For our sample, the dictionary will contain&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;a –&amp;gt; (1 + 2)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;which is then fed in to the CurryVisitor to clone the original lambda’s body (i.e. a + a) while replacing the dictionary key occurrences (a) by the mapped substitution (1 + 2). The new body will be (1 + 2) + (1 + 2), which is hooked up as the body for the new lambda expression with the remaining arguments (in this case none at all) in precisely the same way as in call-by-value.&lt;/p&gt;

&lt;p&gt;What are the characteristics of this approach?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Arguments are not evaluated when they are not needed in the function body for the particular invocation. &lt;/li&gt;

  &lt;li&gt;On the sunny side, too, fatal side effects (denotational bottom) have no effects for unused arguments. &lt;/li&gt;

  &lt;li&gt;But … arguments may be evaluated multiple times, which means side-effects would be multiplied. &lt;/li&gt;

  &lt;li&gt;Also, in order to do the substitution we need to gain access to the function itself, which would be a runtime (in the two senses of the word) task. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h1&gt;Call-by-need&lt;/h1&gt;

&lt;p&gt;As mentioned in &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/08/18/curry-for-dummies-cont-d-a-note-on-purity.aspx"&gt;Curry for dummies cont&amp;#39;d - A note on purity&lt;/a&gt;, call-by-need is an improvement on top of call-by-name. It follows the same principles of substitution but it employ memoization, a caching technique to remember the evaluation result for an expression, to avoid reevaluation expressions. In other words, it eliminates common subexpressions that are introduced by formal parameter substitution. To continue with the same sample, consider:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &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;a&amp;quot;&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;twice = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(a, a), a); &lt;span style="color:green;"&gt;// silly way to double things
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;six = CallByNeed(twice, &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))); &lt;span style="color:green;"&gt;// calling twice with argument (1 + 2)&lt;/span&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;What happens now though is something I’m going to denote using some special syntax. When evaluating twice, it’s rewritten as:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;() =&amp;gt; [| () =&amp;gt; 1 + 2 |] + [| () =&amp;gt; 1 + 2 |]&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The cool thing about denotational semantics is you can invent your own symbols :-). Here I’m introducing what I’d call pillar syntax: i.e. [| … |]. The body of it denotes a parameter-less function using lambda syntax. In practical terms this means we have a delay-loaded or lazy-loaded value: it’s only calculated on-demand. Now by means of common subexpression elimination, the compiler can rewrite this as follows (relying on the fact that the function would be pure, i.e. there are no side-effects that call for the need of doing the evaluation every time again):&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;x = [| () =&amp;gt; 1 + 2 |] 
    &lt;br /&gt;() =&amp;gt; x + x&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The semantics are as follows: when declared (&amp;quot;stage 0” if you want), the function is not evaluated, it’s simply cached. Next, when evaluated for the first time (“stage 1”), the function is called and the value is kept. I’m not building a formal specification here (I’m defining the “valuation function” in words after all), but realize that I’m introducing some state mutation here (let’s not get into monads and beasts like unsafePerformIO this time). On subsequent evaluations, the function isn’t called but the cached value is returned straight away (“stage &amp;gt; 1”). So, applying our function above becomes:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;six() 
    &lt;br /&gt;= let x = [| () =&amp;gt; 1 + 2 |] in x + x 

    &lt;br /&gt;= [| () =&amp;gt; 1 + 2 |] + [| () =&amp;gt; 1 + 2 |] 

    &lt;br /&gt;= [| () =&amp;gt; 3 |] + [| () =&amp;gt; 1 + 2 |] 

    &lt;br /&gt;= [| &lt;font color="#ff0000"&gt;3&lt;/font&gt; |] + [| &lt;font color="#ff0000"&gt;3&lt;/font&gt; |] &lt;font color="#008000"&gt;&amp;#39;here mutation happens; x is a “reference” variable&lt;/font&gt; 

    &lt;br /&gt;= 6&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is precisely what our Cell&amp;lt;T&amp;gt; does. How can we make this work though? What we need is an “environment” in which we keep all the constructed cells. Such an environment establishes bindings between parameters and the corresponding cell that captures the bound expression lifted in a function. This needs some clarification. When calling CallByNeed in the sample above, the argument (1 + 2) needs to be wrapped in a parameter-less function to make it “on-demand” evaluated. The parameter to call “twice” with is:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&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)) &lt;font color="#008000"&gt;// 1 + 2&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and needs to become&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&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))) &lt;font color="#008000"&gt;// () =&amp;gt; 1 + 2&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Next, this lambda needs to be wrapped in a Cell&amp;lt;T&amp;gt;. T is inferred from the type of the parameter, i.e. int, and the constructor of Cell&amp;lt;T&amp;gt; takes in a Func&amp;lt;T&amp;gt;. We can turn a LambdaExpression into a delegate by calling Compile on it. We do this for all the parameters (in the same we only have one) and keep the resulting cells in a dictionary mapping the name of the parameter (a string, in this running sample “a”) onto the corresponding cell. This piece of voodoo plumbing ensures that we have just one reference to a cell per parameter and that’s the whole point of the memoization: we don’t want to reevaluate parameters when they occur in the function body multiple times. To put this in terms of the sample:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;environment = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;();&lt;br /&gt;…&lt;br /&gt;environment[&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;] = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Cell&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(() =&amp;gt; 1 + 2);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;One more question to answer now is how to carry out formal substitution? More specially, what should we replace ParameterExpression occurrences with during the “tree visitation” by the CurryVisitor? The answer isn’t too hard either: a lookup into the environment dictionary, returning a Cell&amp;lt;T&amp;gt;, on which we can call Value causing either evaluation (“stage 1”) or return of the memoized value (“stage &amp;gt; 1”):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;((&lt;span style="color:#2b91af;"&gt;Cell&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;)environment[&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;]).Value&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In other words, our call to twice returns an expression tree like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;() =&amp;gt; ((&lt;span style="color:#2b91af;"&gt;Cell&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;)environment[&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;]).Value&lt;/font&gt; + &lt;font face="Courier New"&gt;((&lt;span style="color:#2b91af;"&gt;Cell&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;)environment[&lt;span style="color:#a31515;"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;]).Value&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You’ll wonder where environment is kept – the answer is in some kind of “closure” that’s created when the lambda expression is compiled, but you can consider this to be an irrelevant detail at this point (if you’re really curious, invoke the Method property on the generated delegate and observe the passed-in ExecutionScope object).&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Time to dive in the code:&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;LambdaExpression &lt;/span&gt;CallByNeed(&lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;func, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] parameters)
{
    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(parameters.Length &amp;gt; func.Parameters.Count)
        &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;Too many parameters specified.&amp;quot;&lt;/span&gt;);

&lt;strong&gt;    &lt;span style="color:blue;"&gt;var &lt;/span&gt;environment = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;();&lt;/strong&gt;
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;assignments = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;ParameterExpression&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;&amp;gt;();

&lt;strong&gt;    &lt;span style="color:#2b91af;"&gt;MethodInfo &lt;/span&gt;envItem = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;, &lt;span style="color:blue;"&gt;object&lt;/span&gt;&amp;gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;get_Item&amp;quot;&lt;/span&gt;);
&lt;/strong&gt;
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; parameters.Length; i++)
    {
        &lt;span style="color:#2b91af;"&gt;ParameterExpression &lt;/span&gt;parameter = func.Parameters[i];
        &lt;span style="color:#2b91af;"&gt;Expression &lt;/span&gt;value = parameters[i];

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(!parameter.Type.IsAssignableFrom(value.Type))
            &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;Incompatible parameter value type for parameter &amp;quot; &lt;/span&gt;+ parameter.Name);

&lt;strong&gt;        &lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;lazyValue = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(value);
        &lt;span style="color:blue;"&gt;object &lt;/span&gt;cell = &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Cell&lt;/span&gt;&amp;lt;&amp;gt;).MakeGenericType(value.Type).GetConstructors()[0].Invoke(&lt;span style="color:blue;"&gt;new object&lt;/span&gt;[] { lazyValue.Compile() });

        environment[parameter.Name] = cell;
        assignments[parameter] = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Property(&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:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(environment), envItem, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(parameter.Name)), &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Cell&lt;/span&gt;&amp;lt;&amp;gt;).MakeGenericType(value.Type)), &lt;span style="color:#a31515;"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt;);
&lt;/strong&gt;    }

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;visitor = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;CurryVisitor&lt;/span&gt;(assignments);
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(visitor.Clone(func.Body), func.Parameters.Skip(parameters.Length).ToArray());
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This is roughly the same as the CallByName implementation (indeed, some refactoring could be done), but the most notable differences (indicated in bold) are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Besides assignments, we’re building up an environment which consists of mappings from parameter.Name strings onto cell objects capturing the lambda built around the parameter expression. &lt;/li&gt;

  &lt;li&gt;The assignments themselves are property .Value calls on the result of retrieving the cell from the environment through the get_Item dictionary indexer, passing in the parameter.Name as the key, and casting the result to Cell&amp;lt;T&amp;gt;. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The substitution using the CurryVisitor is the same as before, only the mappings of ParameterExpressions onto the replacement values are different.&lt;/p&gt;

&lt;p&gt;What are the characteristics of this approach?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Same as call-by-name but: 
    &lt;ul&gt;
      &lt;li&gt;Arguments are evaluated once at most, which brings it closer to call-by-value compared to call-by-name. &lt;/li&gt;

      &lt;li&gt;However, formal substitution is still the driving mechanism here. &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;Also notice we need access to the implementation of the function to do the substitution. This access is not shallow – if a lambda calls into another function, the laziness of arguments needs to be propagated all the way through. When you hit the border where a call into the non-pure lazy world is needed (e.g. interop code), the landscape changes into call-by-value with eager evaluation of the arguments at the call-site. However, laziness is still beneficial because the code in between the function entry point and the interop code much lower in the stack (including OS function calls that are typically call-by-value) might be separated by a bunch of code paths that do not necessarily need to carry on all of the arguments of the original function. In other words, a (not necessarily proper) subset of the input arguments has the potential of getting discarded without any need for evaluation while others will be “degraded” to forced eagerness. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;The final test&lt;/h1&gt;

&lt;p&gt;To test this stuff, I wrote this little test framework:&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;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;LambdaExpression&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[], &lt;span style="color:#2b91af;"&gt;LambdaExpression&lt;/span&gt;&amp;gt;&amp;gt; s_tests&lt;br /&gt;    = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;string&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;LambdaExpression&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[], &lt;span style="color:#2b91af;"&gt;LambdaExpression&lt;/span&gt;&amp;gt;&amp;gt; { { &lt;span style="color:#a31515;"&gt;&amp;quot;By Value&amp;quot;&lt;/span&gt;, CallByValue }, { &lt;span style="color:#a31515;"&gt;&amp;quot;By Name&amp;quot;&lt;/span&gt;, CallByName }, { &lt;span style="color:#a31515;"&gt;&amp;quot;By Need&amp;quot;&lt;/span&gt;, CallByNeed } };

&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Test(&lt;span style="color:blue;"&gt;string &lt;/span&gt;testName, &lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;func, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] parameters)
{
    Test(testName, &lt;span style="color:blue;"&gt;null&lt;/span&gt;, func, parameters);
}

&lt;span style="color:blue;"&gt;static void &lt;/span&gt;Test(&lt;span style="color:blue;"&gt;string &lt;/span&gt;testName, &lt;span style="color:#2b91af;"&gt;Action &lt;/span&gt;cleanUp, &lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;func, &lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;[] parameters)
{
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(testName);
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:blue;"&gt;new string&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;#39;-&amp;#39;&lt;/span&gt;, testName.Length));

    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;test &lt;span style="color:blue;"&gt;in &lt;/span&gt;s_tests.Keys)
    {
        &lt;span style="color:#2b91af;"&gt;LambdaExpression &lt;/span&gt;res = s_tests[test](func, parameters);

        &lt;span style="color:blue;"&gt;try
        &lt;/span&gt;{
            &lt;span style="color:green;"&gt;// this assumes all parameters have been supplied
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;            Console&lt;/span&gt;.Write(test + &lt;span style="color:#a31515;"&gt;&amp;quot; -&amp;gt; &amp;quot; &lt;/span&gt;+ res + &lt;span style="color:#a31515;"&gt;&amp;quot; = &amp;quot;&lt;/span&gt;);&lt;br /&gt;            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(res.Compile().DynamicInvoke());
        }
        &lt;span style="color:blue;"&gt;catch &lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;ex)
        {
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(ex.InnerException.Message);
        }

        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(cleanUp != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
            cleanUp();
    }

    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;As we’re in a functional mood, the use of a dictionary with delegates shouldn’t be too surprising. In essence, s_tests contains mappings of friendly names to delegate instances pointing at each of the CallBy* methods (which all have the same signature). Notice the use of C# 3.0 collection initializers to build up this dictionary. The test execution harness is simple: it iterates over all of the directory entries, extracts the test and calls it with the given lambda expression and the given parameters (assuming all parameters are “eaten” so that we can call DynamicInvoke without passing in any remaining arguments). There’s also support to clean up shared mutable state which comes in handy to compare results.&lt;/p&gt;

&lt;p&gt;Now the tests itself:&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:green;"&gt;    &lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;a = &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;a&amp;quot;&lt;/span&gt;);
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;b = &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;b&amp;quot;&lt;/span&gt;);
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;add = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(a, b), a, b); &lt;span style="color:green;"&gt;// represents (int a, int b) =&amp;gt; a + b
&lt;/span&gt;&lt;span style="color:blue;"&gt;    var &lt;/span&gt;one = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(1);
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;two = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(2);
    Test(&lt;span style="color:#a31515;"&gt;&amp;quot;Add test&amp;quot;&lt;/span&gt;, add, one, two);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;bad = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Divide(one, &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Constant(0));
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;twice = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Lambda(&lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Add(a, a), a, b); &lt;span style="color:green;"&gt;//doesn&amp;#39;t use b
    &lt;/span&gt;Test(&lt;span style="color:#a31515;"&gt;&amp;quot;Eagerness test&amp;quot;&lt;/span&gt;, twice, one, bad);

    &lt;span style="color:blue;"&gt;var &lt;/span&gt;sideEffect = &lt;span style="color:#2b91af;"&gt;Expression&lt;/span&gt;.Call(&lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(&lt;span style="color:#2b91af;"&gt;Program&lt;/span&gt;).GetMethod(&lt;span style="color:#a31515;"&gt;&amp;quot;ChangingMind&amp;quot;&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.NonPublic | &lt;span style="color:#2b91af;"&gt;BindingFlags&lt;/span&gt;.Static), &lt;span style="color:blue;"&gt;null&lt;/span&gt;);
    Test(&lt;span style="color:#a31515;"&gt;&amp;quot;Laziness test&amp;quot;&lt;/span&gt;, () =&amp;gt; { s_i = 0; }, twice, sideEffect, one &lt;span style="color:green;"&gt;/* not used */&lt;/span&gt;);
}

&lt;span style="color:blue;"&gt;static int &lt;/span&gt;s_i = 0;

&lt;span style="color:blue;"&gt;static int &lt;/span&gt;ChangingMind()
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;s_i++;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The first test deals with a pure function – we expect all strategies to come up with the same answer. The second one passes in an unused expression that results in a divide by zero. Call-by-value will crash while the others won’t. Finally, the side-effecting test calls out to a function that has mutating state (which we clean up after every iteration of the test bench since we want to see the effects on a per-strategy basis). This is a bit more subtle. Call-by-value will just call ChangingMind once, before calling the twice function. Call-by-name will duplicate the ChangingMind calls, while call-by-need will still do in-place substitution but because of the memoization with Cell&amp;lt;T&amp;gt; the ChangingMind function is only called once when the parameter is really needed. In fact, it would be a good exercise (left to the reader) to combine the last two tests. Here’s the output:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/CurryfordummiesContdAhappyending_13EBC/image_3.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="352" alt="image" src="http://bartdesmet.info/images_wlw/CurryfordummiesContdAhappyending_13EBC/image_thumb_3.png" width="837" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The results are as expected. Mission accomplished. You can download the code &lt;a href="http://www.bartdesmet.net/download/CallStrategiesSample.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://community.bartdesmet.net/aggbug.aspx?PostID=13890" width="1" height="1"&gt;</description><category domain="http://community.bartdesmet.net/blogs/bart/archive/tags/Functional+programming/default.aspx">Functional programming</category></item><item><title>How C# Array Initializers Work</title><link>http://community.bartdesmet.net/blogs/bart/archive/2008/08/21/how-c-array-initializers-work.aspx</link><pubDate>Fri, 22 Aug 2008 03:05:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:13882</guid><dc:creator>bart</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://community.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=13882</w