GOTO statement in C#.NET

流过昼夜 提交于 2019-12-05 07:56:44

It won't compile because of 'GOTO block' instead of 'goto block;' and even if it was right it won't compile because C# specifications states (§8.9.3):

The target of a goto identifier statement is the labeled statement with the given label. If a label with the given name does not exist in the current function member, or if the goto statement is not within the scope of the label, a compile-time error occurs. This rule permits the use of a goto statement to transfer control out of a nested scope, but not into a nested scope.

Also I found couple specs interesting for me too:

A goto statement cannot exit a finally block (§8.10). When a goto statement occurs within a finally block, the target of the goto statement must be within the same finally block, or otherwise a compile-time error occurs.

And:

A goto statement is executed as follows:

  • If the goto statement exits one or more try blocks with associated finally blocks, >control is initially transferred to the finally block of the innermost try statement. When >and if control reaches the end point of a finally block, control is transferred to the >finally block of the next enclosing try statement. This process is repeated until the >finally blocks of all intervening try statements have been executed.
  • Control is transferred to the target of the goto statement.

the latter means that if you have

try
{
    ...
    goto Label1;
}
finally
{
    CloseAll();
}

Label1:
   MethodB();

it will call CloseAll() before actually transferring control to the Label1 and executing MethodB().

Makes perfect sense, but I never thought about it...

No. block: label must be outside the try in order for the goto to see it. The code won't even compile. Are you taking a test :)?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!