vishwa ratna vishwa ratna - 1 month ago 5
C# Question

goto vs method in finally block in c#

I am particularly aware of C# Reference and have analysed why can't i use goto statement in finally blocks but i wonder when i am trying the same thing with using methods the i am finally able to leave the finally block but according to specification i must not. Isn't the

goto moo
and
static void moo()
doing the same act i.e taking me out of finally block?? So why in first case it is not working but working smooth in second case?


It is a compile-time error for a break, continue, or goto statement to transfer control out of a finally block. When a break, continue, or goto statement occurs in a finally block, the target of the statement must be within the same finally block, or otherwise a compile-time error occurs.


It is a compile-time error for a return statement to occur in a finally block.


First Case with Goto statement.


static void Main(string[] args)
{
try{}
catch (Exception ex){}
finally
{
goto moo;
}
moo:
Console.Write("Hello");
}



Second case with Methods : it worked!


static void Main(string[] args)
{

try{}
catch{}
finally
{
moo();
}
}
static void moo()
{
int x=2, y=3, a=4, b=7;
if (x == y)
return;
else
a = b;
}

Answer

Isn't the goto moo and static void moo() doing the same act i.e taking me out of finally block?

No, absolutely not.

goto moo would transfer control out of the finally block completely.

moo() just calls the method, but then when the method returns you're back in the finally block.

If you put a Console.WriteLine("Still here...") after your moo() method you'll see that.

Comments