3

I have .net 4.5 installed on my box and I understand that below behavior is related to difference in the way foreach captures closure between .net 3.5 and 4.

I'd like to better understand why running the same code in both VS 2012 and then with VS2010 shows different output when I compiling using .net Framework 4 in both cases, is it that VS 2012 runs csc with some special flag that cause it to capture closure?

var words = new[] { "foo", "bar", "baz", "beer" };
var actions = new List<Action>();
foreach (string word in words)
{
    actions.Add(() => Console.WriteLine(word));
}

actions.ForEach(e => e());

Output: With VS2010 and .net 4, above program yields "beer" 4 times

With VS2012 and .net 4:

foo bar baz beer

Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
Rohit Sharma
  • 6,136
  • 3
  • 28
  • 47

2 Answers2

2

The fix for this was not part of .Net 4, it was part of C# 5. Thus, it is the compiler you are using, rather than the framework version you are targeting, that affects the behavior of this code.

This is discussed here, and officially declared here.

Community
  • 1
  • 1
Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
  • Correct me: but isn't .net 4.5 an in place replacement for .net 4. So based on that the compiler bits would be the same irrespective if I run the program from VS 2012 or VS 2010? – Rohit Sharma May 20 '14 at 02:36
  • @RohitSharma - What makes you say 4.5 is a replacement for 4? I don't think it is, it's simply a newer version. 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, and 4.5.2 are all currently supported by Microsoft. You can always target the 4.0 framework in your build in VS 2012 if you want 4.0 behavior; you just can't target 4.5 in 2010. – Tim May 20 '14 at 03:32
  • Please see http://www.hanselman.com/blog/NETVersioningAndMultiTargetingNET45IsAnInplaceUpgradeToNET40.aspx – Rohit Sharma May 20 '14 at 06:25
  • @RohitSharma: changing the target framework doesn't change the compiler, it changes the runtime. – Igby Largeman May 20 '14 at 13:04
0

It was a kine of bug , that Microsoft fix it in VS2012. i don't know, did Microsoft fix it in VS 2010 in Last SP?. if you test it please inform us.

Aqil
  • 360
  • 2
  • 16
  • Not a bug, a design decision. Microsoft changed the design in C# 5, but they did not, and I believe will not, retrofit the change to the earlier compilers. Therefore the C# 4 compiler will always exhibit the original capture behavior. – Chris Taylor May 20 '14 at 02:43