Hey, trying to write a pretty simple piece of code, seeing if there's a bit more elegant way to do this in C#. I'm trying to write a nested for loop, and have a single break statement to break out of the highest for loop.
For instance, in Java this would be done like this:
outerloop: for (int i=0; i<10; i++)
for (int j=0; j<10; j++)
if (condition_met)
break outerloop;
Does C# have a similar method for defining a different loop to break out of than then innermost one
TIA.
-Stephen

Using break with nested loops
Abongs
Maybe if you explain in detail what you're trying to do, rather than looking for a language semantic, someone might be able to offer more details guidance.
enric vives
Assuming the expression computing condition_met isn't changing anything and doesn't rely on variable j, then the condition should be the same after you break out of the inner loop. Therefore you can get rid of that done variable and write it like this:
Of course this will only work if the condition_met expression doesn't alter anything and also doesn't rely on the value of j.
Otherwise, if it was me, I'd write it like this:
rather than making the boolean global to the outer loop, or just use goto as suggested earlier.
Another way to go is to wrap it in a function
or even like this:
SPA
As far as I know, you'd have to use a goto:
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
if (condition_met)
goto outsideloop;
}
}
outsideloop:
This is of course, frowned on, because the keyword is called "goto", but the code is effectively identical the the Java version.
If you are opposed to using a goto, alternately you can force the outer loop to exit:
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
if (condition_met)
{
i = 11;
break;
}
}
}
Redmanmc
frac
Peter, what I'm trying to do is pretty simple. I have a 3x3 grid, with spots being either open or closed. The grid is held in a two-dimensional matrix. The point of the loops is to go through and find the first open spot, then just break out and do some work with those values. If there's a cleaner way to do it than using the goto statement, let me know. I just don't like code looking like this:
bool done = false;
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
if (condition_met)
{
done = true;
break;
}
if (done)
break;
}
Chabs
public point nextOpen()
{
for (int i=0; i<10; i++)
for (int j=0; j<10; j++)
if (condition_met)
return (new point(i,j));
return null;
}
Robert Palmer
waheyluggage
The equivalent of this in C# would be to use a goto but personally I don't like these COBOL situations to control the execution path: