Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using statement and the IDisposable interface

Tags:

c#

vb.net

Is it true that the variables declared within a using statement are disposed together because they are in the scope of the using block?

Do I need to do:

using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation())
{
    using(SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2())
    {

    }
}

or will this be enough and is "bar" disposed together with "foo"?

using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation())
{
    SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2();
}
like image 563
Kees de Wit Avatar asked Dec 05 '22 09:12

Kees de Wit


1 Answers

or will this be enough and is "bar" disposed together with "foo"?

No, bar will not be disposed.

using statement translates into try-finally block, so even if an exception occurs the finally block ensures the call to Dispose method.

Following

using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation())
{
    SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2();
}

Translates into

{
    SomeIdisposableImplementation foo;
    try
    {
        foo = new SomeIdisposableImplementation();
        SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2();
    }
    finally
    {
        if (foo != null)
            foo.Dispose();
    }
}

Leaving bar un-disposed.

like image 107
Habib Avatar answered Dec 31 '22 11:12

Habib