title: Building a LINQ expression tree: how to get variable in scope
body: <p>I'm building a LINQ expression tree but it won't compile because allegedly the local variable <code>$var1</code> is out of scope:</p>
  
  <blockquote>
    <p><em>variable '' of type 'System.Object' referenced from scope '', but it is not defined</em></p>
  </blockquote>
  
  <p>This is the expression tree:</p>
  
  <pre><code>.Block() {
      $var1;
      .If ($n.Property1 == null) {
          .Block() {
              $var1 = null;
              .Return #Label1 { }
          }
      } .Else {
          .Default(System.Void)
      };
      $var1 = (System.Object)($n.Property1).Length;
      .Label
      .LabelTarget #Label1:;
      $var1
  }
  </code></pre>
  
  <p>The following code is responsible for building the tree. It is part of something larger, therefore I don't expect its purpose to be perfectly clear from this example. </p>
  
  <pre><code>MemberExpression sourceExpression = ...;
  
  List&lt;Expression&gt; expressions = new List&lt;Expression&gt;();
  LabelTarget returnTarget = Expression.Label();
  ParameterExpression resultVariable = Expression.Variable(typeof(object));
  
  expressions.Add(resultVariable);
  
  expressions.Add(
      Expression.IfThen(
          Expression.Equal(sourceExpression, Expression.Constant(null)),
          Expression.Block(
              Expression.Assign(resultVariable, Expression.Constant(null)),
              Expression.Return(returnTarget))));
  
  expressions.Add(
      Expression.Assign(
          resultVariable,
          Expression.Convert(sourceExpression, typeof(object))));
  
  expressions.Add(Expression.Label(returnTarget));
  expressions.Add(resultVariable);
  
  Expression finalExpression = Expression.Block(expressions);
  object result = Expression.Lambda&lt;Func&lt;object&gt;&gt;(finalExpression).Compile()();
  </code></pre>
  
  <p>So the question is: how do I get the local variable into scope so that the expression compiles succesfully?</p>