This is more of a hypothetical question, as I am increasingly using .NET 3.5 along with lambda expressions and anonymous delegates. Take this simple example:
static void Main(string[] args)
{
List<int> numList = new List<int>(int[] { 1, 3, 5, 7, 9, 11, 12, 13, 15 });
numList.ForEach(i =>
{
if (i % 2 == 1)
Console.Write(i);
else
return;
});
Console.ReadLine();
}
This will exit:
13579111315
Of course, I really would like to stop executing the ForEach function after 12 and not print 13 or 15. In the traditional foreach construct, you will have a break (instead of returning in my example) and the loop will end. However, the gap in this case is illegal. The following message will appear:
There is no closed loop from which to break or continue
, , , foreach , ?