I understand plenty of questions have been raised and answered or discussed on C# closure. But please spare me a little time on my little experiment ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var timer = new Timer(500))
{
timer.AutoReset = false;
GetFunc2(timer, 0);
// GetFunc3(timer, 0);
timer.Start();
Console.ReadLine();
}
}
static void GetFunc2(Timer timer, int i)
{
for (; i < 5; ++i)
{
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i);
};
}
}
static void GetFunc3(Timer timer, int i)
{
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
timer.Elapsed += (obj, e) =>
{
Console.WriteLine(i++);
};
}
}
}
By calling GetFunc2
and GetFunc3
in the Main
individually, we can see the outputs are different although GetFun3
looks merely like a simple expansion of GetFunc2
. Any one knows why? I think ildasm can reveal the different generated code, but I do want to know why. Tested on VS2012 Pro, .net 4.5.