foreach and IEnumerator

This is a discussion on foreach and IEnumerator within the C# Programming forums, part of the General Programming Boards category; Hello everyone, Two questions, 1. How foreach utilizes the IEnumerator interface and IEnumerable interface? Any there any docuements? I am ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    foreach and IEnumerator

    Hello everyone,


    Two questions,

    1.

    How foreach utilizes the IEnumerator interface and IEnumerable interface? Any there any docuements? I am interested in it.

    2.

    Pros and cons compared with using foreach and using simple index variable to iterate? Like,

    Code:
    for (int i = 0; i < abc.Count; i++)
    {
        // access abc [i] here
    }

    thanks in advance,
    George

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    1)
    "foreach" is just syntactic sugar for:
    Code:
    IEnumerable c; //Some enumerable container
    IEnumerator e = c.GetEnumerator(); //Get enumerator to first element
    
    while(e.MoveNext()) //Loop while there are more elements
    {
       e.Current; //Do something with current element
    }
    2)
    foreach can be used on any enumerable, not just those who can be indexed.
    As for differences in efficinecy I'm sure it depends from case to case.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    1,579
    Thanks Magos,


    I have found some code, share here.

    http://www.csharpfriends.com/Spec/in...cID=15.8.4.htm

    I read the document. There are two expansions for foreach, but I can not distinguish the differences, what are the differences?

    --------------------
    2 If the collection expression is of a type that implements the collection pattern (as defined above), the expansion of the foreach statement is:

    3 Otherwise; the collection expression is of a type that implements System.IEnumerable, and the expansion of the foreach statement is:
    --------------------

    Quote Originally Posted by Magos View Post
    1)
    "foreach" is just syntactic sugar for:
    Code:
    IEnumerable c; //Some enumerable container
    IEnumerator e = c.GetEnumerator(); //Get enumerator to first element
    
    while(e.MoveNext()) //Loop while there are more elements
    {
       e.Current; //Do something with current element
    }
    2)
    foreach can be used on any enumerable, not just those who can be indexed.
    As for differences in efficinecy I'm sure it depends from case to case.

    regards,
    George

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21