foreach and IEnumerator
How foreach utilizes the IEnumerator interface and IEnumerable interface? Any there any docuements? I am interested in it.
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,
"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
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.
I have found some code, share here.
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:
Originally Posted by Magos