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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With