Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6343123
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T20:22:31+00:00 2026-05-24T20:22:31+00:00

Apologies if this question has been asked already, but suppose we have this code

  • 0

Apologies if this question has been asked already, but suppose we have this code (I’ve run it with Mono 2.10.2 and compiled with gmcs 2.10.2.0):

using System;

public class App {
    public static void Main(string[] args) {
        Func<string> f = null;
        var strs = new string[]{
            "foo",
            "bar",
            "zar"
        };

        foreach (var str in strs) {
            if ("foo".Equals(str)) 
                f = () => str;
        }
        Console.WriteLine(f());     // [1]: Prints 'zar'

        foreach (var str in strs) {
            var localStr = str;
            if ("foo".Equals(str))
                f = () => localStr;
        }
        Console.WriteLine(f());     // [2]: Prints 'foo'

        { int i = 0;
        for (string str; i < strs.Length; ++i) {
            str = strs[i];
            if ("foo".Equals(str)) 
                f = () => str;
        }}
        Console.WriteLine(f());     // [3]: Prints 'zar'
    }
}

It seems logical that [1] print the same as [3]. But to be honest, I somehow expected it to print the same as [2]. I somehow believed the implementation of [1] would be closer to [2].

Question: Could anyone please provide a reference to the specification where it tells exactly how the str variable (or perhaps even the iterator) is captured by the lambda in [1].

I guess what I am looking for is the exact implementation of the foreach loop.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T20:22:32+00:00Added an answer on May 24, 2026 at 8:22 pm

    You asked for a reference to the specification; the relevant location is section 8.8.4, which states that a “foreach” loop is equivalent to:

        V v;
        while (e.MoveNext()) {
            v = (V)(T)e.Current;
            embedded-statement
        }
    

    Note that the value v is declared outside the while loop, and therefore there is a single loop variable. That is then closed over by the lambda.

    UPDATE

    Because so many people run into this problem the C# design and compiler team changed C# 5 to have these semantics:

        while (e.MoveNext()) {
            V v = (V)(T)e.Current;
            embedded-statement
        }
    

    Which then has the expected behaviour — you close over a different variable every time. Technically that is a breaking change, but the number of people who depend on the weird behaviour you are experiencing is hopefully very small.

    Be aware that C# 2, 3, and 4 are now incompatible with C# 5 in this regard. Also note that the change only applies to foreach, not to for loops.

    See http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ for details.


    Commenter abergmeier states:

    C# is the only language that has this strange behavior.

    This statement is categorically false. Consider the following JavaScript:

    var funcs = [];
    var results = [];
    for(prop in { a : 10, b : 20 })
    {
      funcs.push(function() { return prop; });
      results.push(funcs[0]());
    }
    

    abergmeier, would you care to take a guess as to what are the contents of results?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Apologies if this question has already been asked but I do not think I
First off, apologies if this question has been asked before but I couldn't find
My sincere apologies if this question has been asked, but I really couldn't find
I apologise if this question has already been asked on here before but I
I know that this question has been asked loads of times, but I have
Apologies if this question has been asked. I couldn't find it, but if it
If this question has already been asked I appologies, please point me in the
Apologies if this is too ignorant a question or has been asked before. A
I apologize if this has already been asked a different way but I couldn't
I feel like this question has probably been asked a thousand times already, so

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.