Search code examples
c#disposeidisposable

Disposing objects in the Destructor


I have an object that has a disposable object as a member.

public class MyClass
{
    private MyDisposableMember member;

    public DoSomething
    {
         using (member = new MyDisposableMember())
         {
             // Blah...
         }
    }
}

There can be many methods in MyClass, all requiring a using statement. But what if I did this instead?

public class MyClass
{
    private MyDisposableMember member = new MyDisposableMember();

    public DoSomething
    {
         // Do things with member :)
    }

    ~MyClass()
    {
        member.Dispose();
    }
}

As you can see, member is being disposed in the destructor. Would this work? Are there any problems with this approach?


Solution

  • Ideally, Dispose() should have already been called prior to finalization. It would be better to follow the typical dispose pattern, and allow the user to Dispose() the object properly, and have the finalizer Dispose of it if dispose has not already been called.

    In this case, since you're encapsulating an IDisposable, you really don't need to implement the finalizer at all, though. (At the the point of finalization, your encapsulated member will get finalized, so there's no need to finalize your object - it just adds overhead.) For details, read this blog article I wrote on encapsulating an IDisposable.