0

I created a list of delegates and add following anonymous delegate for each value of variable i:

delegate {Console.WriteLine(i); }

I was expecting it to print 3 ten times because while invoking each delegate, I am passing 3 as the argument. But, it is printing 10 ten times.

Following is the code:

using System;
using System.Collections.Generic;

namespace ConsoleApplication
{
    public class Program
    {
        static void Main(string[] args)
        {
            ShowUsingDelegates();
            Console.ReadLine();
        }

        delegate void MyDelegate(int i);

        static void ShowUsingDelegates()
        {
            var myDelegates = new List<MyDelegate>();
            for (int i = 0; i < 10; i++)
            {
                myDelegates.Add(delegate {Console.WriteLine(i); });
            }

            foreach (var a in myDelegates)
            {
                a.Invoke(3);
            }
        }
    }
}
Coding man
  • 957
  • 1
  • 18
  • 44
  • 1
    Well, you add the same delegate 10 times to your list. Then you iterate that list and call every delegate resulting in 10 calls. I can´t see your problem. – MakePeaceGreatAgain Jul 20 '18 at 10:55
  • 4
    Possible duplicate of [Captured variable in a loop in C#](https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp) – dymanoid Jul 20 '18 at 10:55
  • 2
    https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/ – Matthew Watson Jul 20 '18 at 10:55
  • 2
    Why do you expect the delegate to pay any attention to anything you pass to `Invoke`. It's not defined to take *any* parameters. – Damien_The_Unbeliever Jul 20 '18 at 10:56
  • Have a look at the compiled version: [sharplab](https://sharplab.io/#v2:D4AQDABCCMDcCwAocVoBYGKQOwIYFsBTAZwAdcBjQiAYQHtti6AbQgQVNOYEsLcAXbgyQBvJBAlQAzFABMqAOzjJYxJPWoAbFDSoAHAAoYYANoBdCLgBOAc2IBKZRoirnzgMoALOgHcAqsTc2DYAIoSsNgIkBvaYbhr0jCyEAHQASoS4ACYAMkGEMXFuAL5IThpZ4YSR/NQgugCyAJ5hEVEGQfwQ3LFlam4w2vUQXr4BQaFVNdGO/c6u8ZIAbtYQ+C1TUcQQALwQ2IQ+EHnE/AA8za3VUQB8heXxAGZ0VhAd2F3cuxBgsN0QZwg0F+3QA1KDZosVA8oWsNm1asQUmwslkDJUEdQRDAAJwdWIQYq9OaLUpYElPF6ZCieN4rV64brYOFXaYOGHzDmLXApACS2CWdAA1gUpMTYYSuWT1GTikA==) – thehennyy Jul 20 '18 at 10:56
  • 1
    Wrong delegate definition, then capturing the global variable for lazy evaluation, nothing is right with this code – Mrinal Kamboj Jul 20 '18 at 11:15

1 Answers1

3

Your delegate is capturing the variable i, which, after your loop, will be 10. You are ignoring the parameter of your delegate (3 in this case). You also named this parameter i in your delegate declaration, but this does not matter if you ignore it when creating a new delegate instance.

Try this instead:

myDelegates.Add(delegate(int x) { Console.WriteLine(x); });
Kwinten
  • 301
  • 1
  • 6