In Java, modifying a local variable like this would result in:
Local variable i defined in an enclosing scope must be final or effectively final
However, the same code translated into c# works as expected
int i = 0;
Timer timer = new Timer(1);
timer.Elapsed += (source, arg) => {
i++;
};
timer.AutoReset = false;
timer.Enabled = true;
Console.WriteLine(i);
System.Threading.Thread.Sleep(100);
Console.WriteLine(i);
0
1
How does this work, and how is it different than the same code in Java? How does the Garbage Collector know when to dispose of variables such as i
?