Dispose vs. finalizers

suggest change

Implement Dispose (and implement IDisposable) so unmanaged or other expensive resources can be released as soon as the object is no longer used. Nothing guarantees that Dispose will be called. A finalizer is also not guaranteed to run: the process can exit first, and the garbage collector never promises to finalize every unreachable object.

One scenario is a program calling Dispose() on objects it explicitly creates:

private void SomeFunction()
{
    // Initialize an object that uses heavy external resources
    var disposableObject = new ClassThatImplementsIDisposable();

    // ... Use that object

    // Dispose as soon as no longer used
    disposableObject.Dispose();

    // ... Do other stuff 

    // The disposableObject variable gets out of scope here
    // The object will be finalized later on (no guarantee when)
    // But it no longer holds the heavy external resource after it was disposed
}

Another scenario is declaring a class to be instantiated by the framework. In this case the new class usually inherits a base class, for instance in MVC one creates a controller class as a subclass of System.Web.Mvc.ControllerBase. When the base class implements IDisposable interface, this is a good hint that Dispose() would be invoked properly by the framework - but again there is no strong guarantee.

Dispose is not a substitute for a finalizer. Use them for different purposes:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents