title: Why does not this delegate work inside the loop?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/3168375/c-using-the-iterator-variable-of-foreach-loop-in-a-lambda-expression-why-fai">C#: using the iterator variable of foreach loop in a lambda expression - why fails?</a>  </p>
  </blockquote>
  
  
  
  <p>I was reading c# reference at MSDN, and I found this..</p>
  
  <p><a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx</a></p>
  
  <p>at the end in comments there is one comment by <code>albionmike</code>
  It goes like this..</p>
  
  <pre><code>When you "catpure" a variable from an outer scope, some counter-intuitive things happen.
  If you run this, you will get an IndexOutOfRange exception during the call f().
  If you uncomment the two commented out lines of code, it will work as expected.
  Hint: Captured Outer Variables have reference rather than value semantics
  
  // Console Project
  using System;
  using System.Collections.Generic;
  using System.Text;
  
  
  namespace EvilDelegation
  {
      delegate void PrintIt();
  
      class Program
      {
  
          static void Main(string[] args)
          {
              string[] strings = { "zero", "one", "two", "three", "four" };
              PrintIt f = null;
              for (int i = 0; i &lt; strings.Length; ++i) {
                  if (i == 2 || i == 3) {
                      // Can you see why this would not work?
                      f = delegate() { Console.WriteLine(strings[i]); };
  
                      // But this does...
                      //int k = i;
                      //f = delegate() { Console.WriteLine(strings[k]); };
  
                  }
              }
              f();
          }
      }
  }
  </code></pre>
  
  <p>I don't get it, why the fist one won't work, and the second one will? In the 4th line, he says: <code>Captured Outer Variables have reference rather than value semantics</code>.<br>
  Okay, fine. But in the for loop, we defined <code>i</code> as an <code>int</code> which of course is a value type, so how can an <code>int</code> type hold a reference? And if <code>i</code> cannot hold reference, that means it is storing value, and if it is storing value, then I don't get why the first one wont work and second one will?<br>
  Am I missing something here?</p>
  
  <p><strong>EDIT :</strong> I think the original author had a typo the call to f() should have been inside the if loop. Please consider that this while answering.</p>
  
  <p><strong>EDIT 2 :</strong> Okay, in case someone might say, it was not a typo, let consider that it was. I wanna know the case where the call to <code>f()</code> is made inside the <code>if</code> clause. Would both run in that case, or just the one not commented?</p>