title: Using the iterator variable of foreach loop in a lambda expression - why fails?
body: <p>Consider the following code:</p>
  
  <pre><code>public class MyClass
  {
     public delegate string PrintHelloType(string greeting);
  
  
      public void Execute()
      {
  
          Type[] types = new Type[] { typeof(string), typeof(float), typeof(int)};
          List&lt;PrintHelloType&gt; helloMethods = new List&lt;PrintHelloType&gt;();
  
          foreach (var type in types)
          {
              var sayHello = 
                  new PrintHelloType(greeting =&gt; SayGreetingToType(type, greeting));
              helloMethods.Add(sayHello);
          }
  
          foreach (var helloMethod in helloMethods)
          {
              Console.WriteLine(helloMethod("Hi"));
          }
  
      }
  
      public string SayGreetingToType(Type type, string greetingText)
      {
          return greetingText + " " + type.Name;
      }
  
  ...
  
  }
  </code></pre>
  
  <p>After calling <code>myClass.Execute()</code>, the code prints the following unexpected response:  </p>
  
  <pre>
  Hi Int32
  Hi Int32
  Hi Int32  
  </pre>
  
  <p>Obviously, I would expect <code>"Hi String"</code>, <code>"Hi Single"</code>, <code>"Hi Int32"</code>, but apparently it is not the case. Why the last element of the iterated array is being used in all the 3 methods instead of the appropriate one? </p>
  
  <p>How would you rewrite the code to achieve the desired goal? </p>