A Portion of Buff

Everybody else had one, so...

You will be enumerated!

Jonathan asks for clarification on IEnumerator behaviour.  No, Reset() is not expected to be called before iteration.  When a new IEnumerator is retrieved from GetEnumerator(), it is expected to be positioned at index -1, before the first element of the collection.  MoveNext() must then be called to advance it to the first element. 

C#'s foreach construct (and VB is probably the same) retrieves a new enumerator from a collection, which is why you can write:

foreach(Foo foo in fooList)
{
    foo.Bar();
}
foreach(Foo foo in fooList)
{
    foo.Baz();
}

and the second loop will still iterate over all elements in the list. However, if you fetch your own enumerator (maybe you want to save a reference to it as an optimisation), you'll have to call Reset() after a full loop if you want to use it again:
FooEnumerator fooEnumerator = fooList.GetEnumerator();
while(listEnumerator.MoveNext())
{
    listEnumerator.Current.Bar();
}
fooEnumerator.Reset();

while(listEnumerator.MoveNext())
{
    listEnumerator.Current.Baz();
}

If you are writing your own IEnumerator, make sure its initial state positions it at index -1.

Comments

Download mp3 online said:

I like foreach loop in php more tha in C#

# December 17, 2007 5:38 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)