Labels and GOTO
s are considered bad practice and as far as I know there is no reason to use it in C#.
What is the use of labels in C#?
Just because they are a disreputable practice, doesn't mean to should close off any possibility of using them. While they may never actually be required, they are occasionally the best way to go.
The use of labels is to support goto
. Bad as goto
may be, if you have goto
in the language, then you need labels. Without goto
, labels are indeed useless in C#.
Sometimes a well placed 'goto' is more elegant/readable than other techniques. Putting 'goto's around when they're not needed is certainly a bad practice. As always, each situation should be judged carefully.
For example, 'goto's can be nice when your function needs to do cleanups in case it fails. You place a label at the end of the function, where you do your cleanup, then 'goto' it in case of a failure.
Nevertheless, 'goto's have become less useful in C# than in C. For example, proper usage of exception handling can obviate the need of 'goto' in some scenarios.
Code generators sometimes use labels and gotos. It can simplify the code generation logic in some cases. Goto statements are generally shunned for readability reasons, but if the code is not intended to be read then that is a moot point.
I have also seen cases where a decompiler gets confused enough by the IL and outputs goto statements instead of the well crafted sequence of instructions that a human would have conjured. If goto statements were not legal then the decompiler might have to completely punt on that section of code. This way, at least, it can generate something that can be round-tripped.
If (audience.LikesGoTo == true) { goto LabelThatSupportGoTo; } else { goto LabelForRejectGoTo; }
There is nothing wrong with labels and goto's in themselves. The problem is that people tend to abuse them which does create a problem.
Typical use of a label
OperationStart:
if ( !TrySomeOperation() ) {
if ( MaybeFixOperation() ) {
goto OperationStart;
}
}
You'd need to make some assertions that you couldn't hit an infitite loop, but given a reasonable set of guarantees there's nothing inherently wrong with this code.