title: C# closure variable scope
body: <p>A(nother?) question about how variable scope is applied in relation to closures. Here's a minimal example:</p>
  
  <pre><code>public class Foo
  {
      public string name;
      public Foo(string name)
      {
          this.name = name;
      }
  }
  
  
  public class Program
  {
      static Action getAction(Foo obj)
      {
          return () =&gt; Console.WriteLine(obj.name); 
      }
  
      static void Main(string[] args)
      {
          Foo obj1 = new Foo("x1");    
          Action a = getAction(obj1);  
          obj1 = new Foo("x2");        
          a();                         
      }
  }
  </code></pre>
  
  <p>This prints <code>x1</code>. It can be explained as:</p>
  
  <p><strong><code>getAction</code> returns an anonymous function which has a closure enclosing the variable <code>obj</code>. <code>obj</code> has the same reference <em>value</em> as <code>obj1</code> but its relationship with <code>obj1</code> ends there as the closure encloses only <code>obj</code>. In other words, whatever value <code>obj1</code> takes afterwards does not affect the closure. Therefore whenever/however <code>a</code> gets called (eg. <code>a</code> gets passed to some other function) it will always print <code>x1</code>.</strong></p>
  
  <p>Now my questions are:</p>
  
  <ol>
  <li>Is the above explanation correct?</li>
  <li>I don't have a specific scenario in mind but what if we wanted the program to print <code>x2</code> (eg. closure to enclose an outer scope)? Could it be done (or doesn't it make sense to even attempt)?</li>
  </ol>