Using statement and the IDisposable interface

c#, vb.net

Solution

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.

Problem

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(); } ```

Original source