0

I am learning delegates in c#. I wrote following code and I expect it to print 1 to 9 but it's printing 10 every time.

private delegate void Printer ();
    static void Main () {
        List<Printer> printers = new List<Printer> ();
        for (int i = 0; i < 10; i++) {
            printers.Add (delegate { Console.WriteLine (i); });
        }

        foreach (var printer in printers) {
            printer ();
        }
    }

Can someone please explain what is happening here?

Vivek Mishra
  • 1,772
  • 1
  • 17
  • 37
  • You have to catch the value inside the for into a variable e.g. `var x = i;` and use that. Let me find the relevant SO question. – tymtam Apr 24 '21 at 12:17
  • 1
    https://stackoverflow.com/questions/35365350/closures-behaving-differently-in-for-and-foreach-loops – tymtam Apr 24 '21 at 12:21
  • 1
    Please also see https://stackoverflow.com/questions/3168375/using-the-iterator-variable-of-foreach-loop-in-a-lambda-expression-why-fails?noredirect=1&lq=1 – tymtam Apr 24 '21 at 12:22
  • cool..... ta... – Vivek Mishra Apr 24 '21 at 12:24

0 Answers0