Alex Rivera | Logout

Is IDisposable.Dispose() called automatically?

Asked 2011-08-06T13:29:21.017
69

Possible Duplicate:
Will the Garbage Collector call IDisposable.Dispose for me?

I have a Class which has some unmanaged resources. My class implements the IDisposable interface and releases the unmanaged resources in the Dispose() method. Do I have to call the Dispose() method or will it be automatically called somehow? Will the Garbage Collector call it?

Edit
Report

2 Answers

11

You will have to call this method manually, maybe (assuming that "MyClass" implements "IDisposable") in a construct like

using(var myclass = new MyClass())
{
   // do something with myclass
}

// now 'myclass'is Disposed

In C# 8.0, you can write as below statement:

using var myclass=new MyClass();

and the "myclass" will be disposed automatically at the end of the scope.

The advantage of the using statement (compared to calling Dispose() explicitly) is that Dispose() is called no matter how you exit this block: by running past the end, encountering a return statement or having an exception thrown.

answered 2011-08-06T13:33:15.570
9

To make sure the resources are correctly disposed, you need to both implement IDisposable and call Dispose in the destructor(finalizer).

class Foo : IDisposable
{
    private bool m_disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~Foo()
    {
        Dispose(false);
    }

    protected void Dispose(bool disposing)
    {
        if (!m_disposed)
        {
            if (disposing)
            { 
                //release managed resources
            }
            //release unmanaged resources

            m_disposed = true;
        }
    }
}
answered 2011-08-06T13:40:55.930

Your Answer