Consider the following C#:
// C# .net
switch(x)
{
case 1:
for(int i = 0; i < 10; i++)
{
int val = getValue(i);
if (val == 0)
goto endswitch;
}
doMoreStuff();
break;
case 2:
doSomeThingElse();
break;
default: throw new ArgumentOutOfRangeException();
}
endswitch: ;
I’ve written code similar to the above code sample. The problem is that I need to break the switch statement from inside the inner for loop. If I put a break statement there, it will only break the inner for loop and then proceed to doMoreStuff(), which is not what I need.
The alternative that seems to work best here is a goto statement, but I know this is frowned upon.
Another alternative is to keep track of a separate variable inside the for loop, but this adds lines of code and is less elegent.
What is the best way to do this?
Update: I have read that there is a way to do this in JavaScript. It works like this: (http://www.devguru.com/technologies/ecmascript/quickref/break.html)
// JavaScript
outer_loop:
for(i=0; i<3; i++)
{
document.write("<BR>" + "outer " + i + ": ");
for(j=0; j<5; j++)
{
document.write("inner " + j + " ");
if(j==x)
break outer_loop;
}
}
Is something like this possible in C#?
You can abstract the check to a method with a return flag:
Just to expand, you can use the goto as you had, but it’s generally frowned upon, especially in such a trivial case. Sometimes it’s useful when you have many, many nested loops or switches but that’s usually a sign that maybe you should refactor/redesign a bit. As you pointed out, you can store a local variable and do a check but that’s a bit obtuse/smelly as you realized. I prefer this method I posted above as it becomes pretty readable to work with.
EDIT: Regarding your comment and edited question, I do not believe a analogous language feature to your JavaScript code exists in C#. From http://msdn.microsoft.com/en-us/library/37zc9d2w%28VS.80%29.aspx (emphasis added):