title: How do I call methods with reference variables with Expression Trees
body: <p>I am trying to figure out how to create an Expression that calls a method which has a reference parameter.</p>
  
  <p>Let me explain my question with a simple (but artificial) example.  Consider the method:</p>
  
  <pre><code>    public static int TwiceTheInput(int x)
      {
          return x*2;
      }
  </code></pre>
  
  <p>I can create an Expression to call the above method by doing something like:</p>
  
  <pre><code>    {
          var inputVar = Expression.Variable(typeof (int), "input");
          var blockExp =
              Expression.Block(
                      new[] {inputVar}
                      , Expression.Assign(inputVar, Expression.Constant(10))
                      , Expression.Assign(inputVar, Expression.Call(GetType().GetMethod("TwiceTheInput", new[] { typeof(int) }), inputVar))
                      , inputVar
                      );
          var result = Expression.Lambda&lt;Func&lt;int&gt;&gt;(blockExp).Compile()();
      }
  </code></pre>
  
  <p>On execution, the "result" above should end up with a value of 20.
  Now consider a version of TwiceTheInput() that uses by-reference parameters:</p>
  
  <pre><code>    public static void TwiceTheInputByRef(ref int x)
      {
          x = x * 2;
      }
  </code></pre>
  
  <p>How do I write a similar Expression Tree to call TwiceTheInputByRef() and pass arguments by reference to it?</p>
  
  <p>Solution:   (Thanks to Cicada).  Use:</p>
  
  <pre><code>Type.MakeByRefType()
  </code></pre>
  
  <p>Here's a code segment to generate the Expression Tree:</p>
  
  <pre><code>        {
          var inputVar = Expression.Variable(typeof(int), "input");
          var blockExp =
              Expression.Block(
                      new[] { inputVar }
                      , Expression.Assign(inputVar, Expression.Constant(10))
                      , Expression.Call(GetType().GetMethod("TwiceTheInputByRef", new[] { typeof(int).MakeByRefType() }), inputVar)
                      , inputVar
                      );
          var result = Expression.Lambda&lt;Func&lt;int&gt;&gt;(blockExp).Compile()();
      }
  </code></pre>