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();
}
}