title: Prevent .NET from "lifting" local variables
body: <p>I have the following code:</p>
  
  <pre><code>string prefix = "OLD:";
  Func&lt;string, string&gt; prependAction = (x =&gt; prefix + x);
  prefix = "NEW:";
  Console.WriteLine(prependAction("brownie"));
  </code></pre>
  
  <p>Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console.</p>
  
  <p>Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression?  I would like a way of making my Func work identically to:</p>
  
  <pre><code>Func&lt;string, string&gt; prependAction = (x =&gt; "OLD:" + x);
  </code></pre>
  
  <p>The reason I need this is I would like to serialize the resulting delegate.  If the prefix variable is in a non-serializable class the above function will not serialize.  </p>
  
  <p>The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method:</p>
  
  <pre><code>string prefix = "NEW:";
  var prepender = new Prepender {Prefix = prefix};
  Func&lt;string, string&gt; prependAction = prepender.Prepend;
  prefix = "OLD:";
  Console.WriteLine(prependAction("brownie"));
  </code></pre>
  
  <p>With helper class:</p>
  
  <pre><code>[Serializable]
  public class Prepender
  {
      public string Prefix { get; set; }
      public string Prepend(string str)
      {
          return Prefix + str;
      }
  }
  </code></pre>
  
  <p>This seems like a lot of extra work to get the compiler to be "dumb".</p>