using 'foreach' and continue looping in another function?

  • Thread starter Thread starter John Dalberg
  • Start date Start date
J

John Dalberg

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
 
Yeah, that's a poor (demonicly evil) practice. .NET should help you
out by preventing that.
 
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top