Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lambda use local variable

Tags:

c#

lambda

class Program
    {        
        static Action act = null;

        static void Main(string[] args)
        {
            Test();
            act();
            act();
            Test();
            act();
        }   

        static void Test()
        {
            int count = 0;

            if(act == null) act = () => Console.Write(++count + " ");
        }
    }  

result : 1 2 3 why?

if delete [ if(act == null) ] result : 1 2 1

like image 545
Snow Avatar asked Dec 05 '22 09:12

Snow


1 Answers

Currently, you're only creating a single delegate instance. That captures the local variable that was declared in the Test method the first time it was called.

That local variable effectively has an extended lifetime due to the delegate that captures it. Every time you invoke the delegate, it increments the same variable.

When you remove the if (act == null) condition, you create a new delegate each time you call Test, which means it captures a different count local variable, starting at 0 each time. You're calling Test() twice, and the delegate created through the first call is invoked twice (with output 1 then 2). The delegate create through the second call is only invoked once (with output 1).

like image 120
Jon Skeet Avatar answered Dec 27 '22 23:12

Jon Skeet