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 6558957
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T13:15:48+00:00 2026-05-25T13:15:48+00:00

Possible Duplicate: How do foreach loops work in C#? I’ve been searching the internet

  • 0

Possible Duplicate:
How do foreach loops work in C#?

I’ve been searching the internet and I’m having trouble finding any answers as to what’s really going on behind the scenes with the foreach loop in C#.

I know this question doesn’t really pertain to actually coding but its bothering me. I’m pretty new to OO programming and especially interfaces. I understand they are contracts and I understand how IEnumerable and IEnumerator work – or so I think.

I’ve been reading this article on MSDN:
IEnumerable Interface

I understand how everything is set up. I’m a little unclear though in the Main loop how the foreach knows to itterate through all the values in _people. How does it know this? How does it keep track of Current by just calling return new PeopleEnum(_people);?

EDIT: I don’t see how this is an exact duplicate. Yes its similar grounds and the same question is being asked but we are looking for different answers or the answer I wanted was not discussed in the previous question.

A foreach loop like foreach(int i in obj) {…} kinda equates to

… is “kinda” not the answer I’m looking for.

  • 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-25T13:15:49+00:00Added an answer on May 25, 2026 at 1:15 pm

    I encourage you to read section 8.8.4 of the C# specification, which answers your question in detail. Quoting from it here for your convenience:


    A foreach statement of the form

    foreach (V v in x) embedded-statement
    

    is then expanded to:

    {
        E e = ((C)(x)).GetEnumerator();
        try 
        {
            V v;
            while (e.MoveNext()) 
            {
                v = (V)(T)e.Current;
                embedded-statement
            }
        }
        finally 
        {
             code to Dispose e if necessary
        }
    }
    

    The types E, C, V and T are the enumerator, collection, loop variable and collection element types deduced by the semantic analyzer; see the spec for details.

    So there you go. A “foreach” is just a more convenient way of writing a “while” loop that calls MoveNext until MoveNext returns false.

    A few subtle things:

    • This need not be the code that is generated; all that is required is that we generate code that produces the same result. For example, if you “foreach” over an array or a string, we just generate a “for” loop (or loops, in the case of multi-d arrays) that indexes the array or the chars of the string, rather than taking on the expense of allocating an enumerator.

    • If the enumerator is of value type then the disposal code might or might not choose to box the enumerator before disposing it. Don’t rely on that one way or the other. (See http://blogs.msdn.com/b/ericlippert/archive/2011/03/14/to-box-or-not-to-box-that-is-the-question.aspx for a related issue.)

    • Similarly, if the casts automatically inserted above are determined to be identity conversions then the casts might be elided even if doing so would normally cause a value type to be copied.

    • Future versions of C# are likely to put the declaration of loop variable v inside the while loop body; this will prevent the common “modified closure” bug that is reported about once a day on Stack Overflow. [Update: This change has indeed been implemented in C# 5.]

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

Sidebar

Related Questions

Possible Duplicate: How does foreach work when looping through function results? If I have
Possible Duplicate: How does foreach work when looping through function results? Title has the
Possible Duplicate: What Ruby IDE do you prefer? I've generally been doing stuff on
Possible Duplicate: How does the Google Did you mean? Algorithm work? Suppose you have
Possible Duplicate: Breaking out of a nested loop I have this code foreach (___)
Possible Duplicate: Array versus List<T>: When to use which? Is there any best practice
Possible Duplicate: LINQ equivalent of foreach for IEnumerable<T> please help me to figure out
Possible Duplicate: Why is there not a ForEach extension method on the IEnumerable interface?
Possible Duplicate: Multiple index variables in PHP foreach loop Can we echo multiple arrays
Possible Duplicate: Foreach can throw an InvalidCastException? Consider the following block of code public

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.