I don't know how to explain the problem exactly in word. I have written the code to reproduce the problem, and I have tried my best to make the code easy to read.
delegate string del();
static void Main(string[] args)
{
string[] ss = { "a", "b" };
Dictionary<string, del> dic = new Dictionary<string, delSS>();
foreach (string s in ss) {
dic[s] = () => s;
}
foreach (string s in ss) {
System.Console.WriteLine("{0}:{1}", s, dic[s]());
}
System.Console.ReadLine();
}
I created two lambda expression for "a" and "b", for "a", it returns "a", and for "b", it returns "b". The delegates are saved in a dictionary named dic. And I call them by dics. The expected result is
a:a
b:b
and this is the result in VS2013. But in VS2008, the result is
a:b
b:b
I have tried the versions of .Net Framework from 3.0 to 4.5 in VS2013, and all of them gives the same result. I also tried the 3.0 and 3.5 in VS2008, and they gives same results too. I thought it means it's not a bug of the Framework, but bug of Compiler. I'm developing an application for WinCE 6.0, which is only supported in VS2008 and earlier versions. That's why I have to use VS2008. I found the problem when I'm debugging the WinCE application. I thought it's a bug of Compact Framework, but it's proved to be a bug of VS2008. Does anyone know how to fix it?