ForEach() : Why can't use break/continue inside

Rami Shareef picture Rami Shareef · Dec 14, 2010 · Viewed 34.5k times · Source

Since ForEach() method loop through all a list members, Why cant use a break/continue clause while i can use them inside a normal foreach loop

lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);

Error:

"No enclosing loop out of which to break or continue"

Answer

Femaref picture Femaref · Dec 14, 2010

Because ForEach is a method and not a regular foreach loop. The ForEach method is there for simple tasks, if you need to break or continue just iterate over lstTemp with a regular foreach loop.

Usually, ForEach is implemented like this:

public static ForEach<T>(this IEnumerable<T> input, Action<T> action)
{
  foreach(var i in input)
    action(i);
}

As it is a normal method call, action doesn't know anything about the enclosing foreach, thus you can't break.