Alex Rivera | Logout

Who Disposes of an IDisposable public property?

Asked 2009-03-23T19:26:12.473
33

If I have a SomeDisposableObject class which implements IDisposable:

class SomeDisposableObject : IDisposable
{
    public void Dispose()
    {
        // Do some important disposal work.
    }
}

And I have another class called AContainer, which has an instance of SomeDisposableObject as a public property:

class AContainer
{
    SomeDisposableObject m_someObject = new SomeDisposableObject();

    public SomeDisposableObject SomeObject
    {
        get { return m_someObject; }
        set { m_someObject = value; }
    }
}

Then FxCop will insist that AContainer is also made IDisposable.

Which is fine, but I can't see how I can safely call m_someObject.Dispose() from AContainer.Dispose(), as another class may still have a reference to the m_someObject instance.

What is the best way to avoid this scenario?

(Assume that other code relies on AContainer.SomeObject always having a non-null value, so simply moving the creation of the instance outside of the AContainer is not an option)

Edit: I'll expand with some example as I think some commenters are missing the issue. If I just implement a Dispose() method on AContainer which calls m_someObject.Dispose() then I am left with these situations:

// Example One
AContainer container1 = new AContainer();
SomeDisposableObject obj1 = container1.SomeObject;
container1.Dispose();
obj1.DoSomething(); // BAD because obj1 has been disposed by container1.

// Example Two
AContainer container2 = new AContainer();
SomeObject obj2 = new SomeObject();
container2.SomeObject = obj2; // BAD because the previous value of SomeObject not disposed.
container2.Dispose();
obj2.DoSomething(); // BAD because obj2 has been disposed by container2, whic
Edit
Report

1 Answer

1

An interesting thing that I've encountered is that SqlCommand owns an SqlConnection (both implement IDisposable) instance usually. However calling dispose on the SqlCommand will NOT dispose the connection too.

I've discovered this also with the help of Stackoverflow right here.

So in other words it matters if the "child" (nested?) instance can/will be reused later.

answered 2009-03-24T12:22:19.927

Your Answer