By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,224 Members | 1,233 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,224 IT Pros & Developers. It's quick & easy.

using 'foreach' and continue looping in another function?

P: n/a
In a traditional for loop, one can use the index (say i) and continue
looping in another function and come back to original for loop (even though
it's not good practice)

Can the newer foreach enumerator do the same.. how to continue looping in
another function and return to the original foreach starting from where you
ended in the second foreach? My guess it's not possible.

John Dalberg
Mar 24 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Yeah, that's a poor (demonicly evil) practice. .NET should help you
out by preventing that.

Mar 24 '06 #2

P: n/a
The following bits of code are equivalent:

foreach (MyType t in thing.OtherThings)
{
... do something ...
}

IEnumerator enumerator = thing.OtherThings.GetEnumerator();
while (enumerator.MoveNext())
{
MyType t = (MyType)enumerator.Current;
... do something ...
}

Using the second syntax, there is nothing stopping you from passing the
enumerator to another method and continuing the enumerator there:

IEnumerator enumerator = thing.OtherThings.GetEnumerator();
while (enumerator.MoveNext())
{
MyType t = (MyType)enumerator.Current;
...
otherObject.SomeMethod(enumerator);
...
}

where

public void SomeMethod(IEnumerator enumerator)
{
do
{
MyType t = (MyType)enumerator.Current;
if (SomeCondition(t))
{
... do some stuff with t ...
}
}
while (!SomeCondition(t) && enumerator.MoveNext)
}

That said, this is sort of counterintuitive and will be difficult to
maintain. If you find that you have to resort to this sort of thing, it
should be only after having exhausted all of the "reasonable" options.

Mar 24 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.