I agree, in your case Rick's solution is really the best.
However, if you want to exit the for loop in some cases but not in some
other, you could put the loop and switch inside a method and use the return
statement:
private void myFunction(bool[] myArray)
{
for (int i=0; i<myArray.Length; i++)
{
Console.WriteLine(i);
if (myArray[i] == true)
switch (i)
{
case 0:
Console.WriteLine("Case 0");
return;
case 1:
Console.WriteLine("Case 1");
break;
default:
Console.WriteLine("Default");
break;
}
}
}
However, my opinion is that using break in a loop really is a jump statement
and should be used carefully.... you can always implement the desired
behaviour using flags and a while loop... most languages do not have a break
statement for terminating loops and this is how you implement that behaviour
in them. By naming the flag with a meaningful name your code will be more
readable, using break may not always be so clear, for instance if you have
nested loops. In other words, I prefer Oliver's solution over mine above.
"PeterZ" wrote:
Thanks guys!
I my particular case, I think Rick's is the most simple, but I can see where
on other occasions the other suggestions would be more appropriate - eg.
where you only wanted to exit the loop in a specific case statement rather
than all of them.
Thanks again!
PeterZ
"PeterZ" <_r**********************@hotmail.com> wrote in message
news:eB*************@tk2msftngp13.phx.gbl...
Hi,
Back to basics!
My understanding is that the only way to exit a For-Next loop prematurely is
with the 'break' keyword. How are you supposed to do that if you're inside
a Switch statement? The break keyword will only come out of the switch, not
the for-next loop.
for (int i=0; i<=myArray.Length; i++)
{
if (myArray[i] == true)
switch (i)
{
case 0 :
... do somehting
exit the for loop;
case 1 :
... do somehting
exit the for loop;
case 2 :
... do somehting
exit the for loop;
}
}
Cheers,
PeterZ