40 votesDaryl commented
A much better option, which other languages support, is to use labels. See this suggestion:
foreach (string fileName in fileList)
if (someCondition) continue FileLoop; // done with this file
This is much safer than goto -- if the label doesn't refer to a loop statement, using break or continue is a compile-time error.
More maintainable -- counting loop levels and using an int is asking for trouble. Someone might add a loop level without noticing the break(2). Or remove a loop level. Or copy the code with the break(2) to a different place... etc. This is a bad idea.
Works with existing syntax. The new syntax is a proper superset of the existing syntax. No lexical weirdness like they had with "async" and LINQ would be needed.
7 votesDaryl supported this idea ·Daryl commented
ALL break and continue statements are just different notations of a goto statement. A break is a goto which targets the first statement after the loop block. A continue targets the end of the loop block itself.
The whole point of loop control statements is that they're easier to understand and maintain than goto's; however you are correct that we could just use goto's everywhere and achieve the same effect. That's why we should allow developers to break or continue a specific loop, rather than only the innermost: to avoid using a goto.Daryl shared this idea ·