spgilmore

spgilmore

  • NA
  • 591
  • 0

IEnumerator not reset?

Jun 20 2006 2:26 PM
I have a strongly typed collection that I wrote.  It implements IEnumerable and IEnumerator.  As far as I can see, I have the same code as every example on the internet.  It works, sort-of.  Here's part of the enumerator.

public IEnumerator GetEnumerator()
{
return this;
}

protected int fCurrent;
public object Current
{
get { if (fCurrent < fItems.Count) return fItems[fCurrent]; else return null; }
}

public bool MoveNext()
{
if (fCurrent < fItems.Count-1)
{
fCurrent++;
return true;
}
else return false;
}

public void Reset()
{
fCurrent = -1;
}
}





The problem is that it works in a foreach loop only once.  I can have a collection with 10 items.  In the first foreach loop, the fCurrent position is -1 (I call Reset() in the constructor).  At the end of the foreach loop, fCurrent is on the last element, 9.  This is expected.

In the next foreach loop, the first time MoveNext is called, it returns false because fCurrent is still 9, and the loop executes 0 iterations.  If I prefix the foreach loop with a .Reset(), then it works as expected.

I thought that the foreach loop would invoke a call to Reset().  It doesn't.  Should it?  Do I have to called Reset() before each foreach loop, or am I doing something wrong?