Anonymous delegates getting wrong variables when created in a foreach loop in VS2010 - by Chris Pauly

Status : 


Sign in
to vote
ID 778842 Comments
Status Active Workarounds
Type Bug Repros 0
Opened 2/8/2013 9:50:17 AM
Access Restriction Public


I have a function that creates a bunch of toolstripitems based on a list of strings.  I create those click events on the toolstripitem as an anonymous function, and I use the string value in my anonymous function.

It is a .NET 4 application.

When I compile that on a VS2010 SP1 (10.0.40219.1 SP1Rel), the string value that is used is the one that was set during the last pass through the foreach loop.

When I compile that on a VS2012 U1 (11.0.51106.01 Update 1), the string value that is used is the one that was set during the current enumeration on the list in the foreach loop.

This appears to also be related specifically to using a foreach loop.  When I switched my code to a for loop and declare a local variable inside that loop to assign my string to, it worked correctly in VS2010.
Sign in to post a comment.
Posted by Microsoft on 2/10/2013 at 6:16 PM
The product team itself no longer directly accepting feedback for Microsoft Visual Studio 2010 and earlier products. You can get support for issues with Visual Studio 2010 and earlier by visiting one of the resources in the link below:
Posted by Microsoft on 2/8/2013 at 10:50 AM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(
Posted by Chris Pauly on 2/8/2013 at 10:23 AM
I don't read IL... but I just did a diff between the working and non-working versions of this code. I noticed that there is a chunk of IL in the VS2012 compile of the code that appears to exist within the foreach loop, and in the VS2010 version, it happens before the foreach loop.

    IL_0046: ldnull
    IL_0047: stloc.2
    IL_0048: newobj     instance void AnonymousDelegatesIssueInVS2010.Form1/'<>c__DisplayClass2'::.ctor()
    IL_004d: stloc.3

That looks like a very suspect bit of IL that may cause this issue if not added to the loop in IL.