2

Here is the sample code.

var values = new List<string>() { "Stack", "Over", "Go" }; var funcs = new List<Func<string>>(); foreach(var v in values) funcs.Add( ()=>v ); foreach(var f in funcs) Console.WriteLine(f()); 

When I ran this code with visual studio 2010 I got the output as: Go Go Go

But when I tried the same code in visual studio 2012 the output was: Stack Over Go

Why is it behaving differently?

9
  • 5
    Can you make sure the code you provide matches your stated output. It seems somewhat unlikely that the above code would ever generate either "stupid stupid stupid" or "Bob is stupid" Commented Feb 25, 2013 at 11:33
  • WHAT?? How even possible output of this code could stupid stupid stupid or Bob is stupid ? Commented Feb 25, 2013 at 11:33
  • 2
    I suspect it would generate Go Go Go and Stack Over Go, but post the code which is generating the output you have mentioned. Commented Feb 25, 2013 at 11:34
  • var values = new List<string>() { "Bob", "is", "stupid" }; Commented Feb 25, 2013 at 11:34
  • 1
    -1 for posting fake code. Don't do that! Commented Feb 25, 2013 at 11:34

1 Answer 1

9

The reason is that the compiler was changed to create a temporary copy of variables captured in a closure.

Take the following code in VS 2012:

foreach(var v in values) funcs.Add(() => v); 

The code the VS 2012 compiler generates from this is equivalent to code generated by the VS 2010 compiler for this code:

foreach(var v in values) { var tmp = v; funcs.Add(() => tmp); } 

The reason for this change was the fact that many developers found the behaviour of the VS 2010 compiler unexpected.

Sign up to request clarification or add additional context in comments.

8 Comments

+1. See also: Eric Lippert's blog post on this topic: blogs.msdn.com/b/ericlippert/archive/2009/11/12/…
It's so nice to stop making loop copies of variables everywhere - always felt so dumb having to do it all the time.
@Ergwun: Thanks - I was just searching for that link to add something official.
Well if we're going for official then the page that tells you the differences between C# in Visual Studio 2010 and C# in Visual Studio 2012 would be a good resource to look at/Google for.
@ta.speot.is: I am not really sure how to take your comment. If you are implying that I am lazy - that's laughable. If you are implying that the OP is lazy - that's debatable, but also not really fair. As a beginner, he most likely will be overwhelmed with the search results and the overview page.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.