0

I feel like I should know exactly how this works since I use it regularly and it seems to work, but I don't. As an example, how would this behave:

void MyMethod()
{    
    for(int i = 0; i < 100; i++)
    {
        DoSomeWork(() =>
        {
            Console.WriteLine(i);
        });
    }
}

How does the scope of i change? Is the value copies over to the callback or does the callback function have access to the variable when it is called? Will the variable thus be in memory after MyMethod has long been finished?

Is there a good explanation for these kinds of things, especially when using lambda and async methods?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
pixartist
  • 1,137
  • 2
  • 18
  • 40
  • Man this site has changed – pixartist Jul 16 '15 at 12:15
  • This is called a `closure`. http://csharpindepth.com/articles/chapter5/closures.aspx – Romain Meresse Jul 16 '15 at 12:16
  • 4
    I think this is a perfectly reasonable question - but I suspect it's a duplicate. Trying to find one now. – Jon Skeet Jul 16 '15 at 12:16
  • 3
    @roryap: The question asks for an explanation - while that *could* be an off-site resource, I think it's reasonable for it to be in an answer, too. – Jon Skeet Jul 16 '15 at 12:17
  • The capturing (or anything else about 'scope') is not related to `async` – H H Jul 16 '15 at 12:18
  • The question I've marked this as a duplicate of refers to anonymous methods, but the principle is exactly the same - hope it helps you. – Jon Skeet Jul 16 '15 at 12:19
  • @Henk I know it#s not related, but it's very useful in the case of async function and async allows for a delayed execution of the lambda expression when the main method should be done with its code – pixartist Jul 16 '15 at 12:19
  • Well the duplicate thread does not really help me to understand my code since he actually creates copies of the outer variables in his code while I use them as parameters in a function call. Do I need to decompile my code to get an answer ? – pixartist Jul 16 '15 at 12:22
  • @JonSkeet -- I stand corrected. I read the question too quickly. – rory.ap Jul 16 '15 at 12:57
  • There are dozens more duplicates, take your pick. You will find reading a few of them, or a tutorial, is much quicker then understanding the decompiled IL. Look for "captured" and/or "closed over" – H H Jul 17 '15 at 16:07

0 Answers0