TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
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?
Reply
Answers (
0
)
Invalid operation. the connection is closed.
Object reference not set to an instance of an object.