Goto in Spirit But Not in Name
I’ve heard statements like “good programmer should never use goto” a million times. Due to various reasons, some good and some bad, goto command is really hated. I would say it’s hated so much that quite a few young programmers are even not aware of its existence. It’s existence in C# is treated as measels. And, just like measels, it’s making a comeback.
First of all, why would you use goto? For example, if we’re checking something deep in loops, there is no easier way to exit than a humble goto. Consider the following code:
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 100; j++) {
if (something) { goto Done; }
}
}
Done:
// proceed with other codeYes, you can get the same effect by using break at each level but this is definitely a nicer way to do it. And I would argue that this is NOT a misuse of goto. Regardless, C# 15 is preparing a death nail for this usage too.
New feature is called Labeled break and continue. In C# 15, my example above would now look like this:
Work:
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 100; j++) {
if (something) { break Work; }
}
}
// proceed with other codeI would argue this is a goto in disguise. Just a syntactic sugar that changes what gets labeled but doesn’t really change the flow.
That said, I am not really against it. I see how in many situations it will be more expressive than goto was. Maybe it’s time for goto to retire.
I for one welcome “Labeled break and continue” aka goto2. :)