What is the use of labels in C#?

前端 未结 13 2232
面向向阳花
面向向阳花 2020-12-17 20:18

Labels and GOTOs 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#?

13条回答
  •  星月不相逢
    2020-12-17 21:02

    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.

提交回复
热议问题