Search code examples
c#vb.netdisposeusing-statement

Are all disposable objects instantiated within a using block disposed?


This is a question I have asked myself many times in the past as I nested using statements 5 deep.

Reading the docs and finding no mention either way regarding other disposables instantiated within the block I decided it was a good Q for SO archives.

Consider this:

using (var conn = new SqlConnection())
{
    var conn2 = new SqlConnection();
}

// is conn2 disposed?

Solution

  • Obviously I have the answer... ;-)

    The answer is no. Only the objects in the using declaration are disposed

    [Test]
    public void TestUsing()
    {
        bool innerDisposed = false;
        using (var conn = new SqlConnection())
        {
            var conn2 = new SqlConnection();
            conn2.Disposed += (sender, e) => { innerDisposed = true; };
        }
    
        Assert.False(innerDisposed); // not disposed
    }
    
    [Test]
    public void TestUsing2()
    {
        bool innerDisposed = false;
        using (SqlConnection conn = new SqlConnection(), conn2 = new SqlConnection())
        {
            conn2.Disposed += (sender, e) => { innerDisposed = true; };
        }
        Assert.True(innerDisposed); // disposed, of course
    }