foreach and IEnumerator [Archive] - C Board

PDA

View Full Version : foreach and IEnumerator


George2
04-30-2008, 03:56 AM
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,


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



thanks in advance,
George

Magos
04-30-2008, 05:00 AM
1)
"foreach" is just syntactic sugar for:

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.

George2
04-30-2008, 08:01 AM
Thanks Magos,


I have found some code, share here.

http://www.csharpfriends.com/Spec/index.aspx?specID=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:
--------------------

1)
"foreach" is just syntactic sugar for:

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