Search code examples
c#classconstructordispose

Should I Dispose Object Passed Through Constructor If Other Constructors Create It?


Given the following code, should I only dispose foo when it was created by within the Bar class? Or should I always dispose foo even when it was passed to a constructor? I'm thinking I should probably add another private variable to keep track of whether Bar created foo or whether it was passed to the Bar( Foo foo ) constructor, and only dispose of foo when it was created by the public Bar( string name ) constructor.

public class Bar: IDisposable
{
    private Foo foo = null;

    public Bar( string name )
    {
        this.foo = new Foo(name);
    }
    public Bar( Foo foo )
    {
        this.foo = foo;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    protected virtual void Dispose( bool disposing )
    {
        if( disposed )
            return;
        if( disposing )
            foo.Dispose();
        this.disposed = true;
    }
}

Solution

  • You're correct in your thinking.

    If you're passed an instance of Foo from elsewhere, and dispose of it yourself, you might break code still consuming the Foo. If you create an instance of Foo but don't dispose of it, you'll hang on to the memory it consumes unnecessarily long.

    So, your best option is to track whether you created the instance yourself and dispose of it if so. (You could also allow the caller to specify the behaviour, as has been mentioned in the comments.)

    (Alternatively, you could not do anything, which will be more inefficient but will at least not break anything. The only solution that is likely to actively break something is if you dispose of the instance that's been passed in from elsewhere.)