Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GOTO inside using block, will the object get disposed?

Tags:

c#

.net

.net-4.0

I'm quite unsure about using goto inside an using block.

For example:

using(stream s = new stream("blah blah blah"));
{
    //do some stuff here

    if(someCondition) goto myLabel;
}

Now if someCondition is true the code execution will move on to myLabel, but, will the the object get disposed?

I've seen some pretty good questions here on this topic but they all talk about different things.

like image 430
Sean Vaughn Avatar asked Dec 01 '25 06:12

Sean Vaughn


2 Answers

Yes.


But why not try it yourself?

void Main()
{
    using(new Test())
    {
        goto myLabel;
    }
myLabel:
    "End".Dump();
}
class Test:IDisposable
{
    public void Dispose()
    {
        "Disposed".Dump();
    }
}

Result:

Disposed
End

like image 57
sloth Avatar answered Dec 03 '25 20:12

sloth


The using statement is essentially a try-finally block and a dispose pattern wrapped up in one simple statement.

using (Font font1 = new Font("Arial", 10.0f))
{
    //your code
}

Is equivalent to

Font font1 = new Font("Arial", 10.0f);
try
{
     //your code
}
finally
{
     //Font gets disposed here
}

Thus, any jump from the "try-block", be it throwing an exception, the use of goto (unclean!) &tc. will execute the Disposal of the object being used in that "finally" block..

like image 40
The Forest And The Trees Avatar answered Dec 03 '25 18:12

The Forest And The Trees



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!