Search code examples
.netfinalizer

Can code be run when an object falls out of scope in .Net?


Is there any way to "automatically" run finalization / destructor code as soon as a variable loses scope in a .Net language? It appears to me that since the garbage collector runs at an indeterminate time, the destructor code is not run as soon as the variable loses scope. I realize I could inherit from IDisposable and explicitly call Dispose on my object, but I was hoping that there might be a more hands-off solution, similar to the way non-.Net C++ handles object destruction.

Desired behavior (C#):

public class A {
    ~A { [some code I would like to run] }
}

public void SomeFreeFunction() {
    SomeFreeSubFunction();
    // At this point, I would like my destructor code to have already run.
}

public void SomeFreeSubFunction() {
    A myA = new A();
}

Less desirable:

public class A : IDisposable {
    [ destructor code, Dispose method, etc. etc.]
}

public void SomeFreeFunction() {
    SomeFreeSubFunction();
}

public void SomeFreeSubFunction() {
    A myA = new A();
    try {
        ...
    }
    finally {
        myA.Dispose();
    }
}

Solution

  • The using construct comes closest to what you want:

    using (MyClass o = new MyClass()) 
    {
     ...
    }
    

    Dispose() is called automatically, even if an exception occurred. But your class has to implement IDisposable.

    But that doesn't mean the object is removed from memory. You have no control over that.