Is there a way to "automatically" run the completion / destructor code as soon as the variable loses its scope in the .NET language? It seems to me that since the garbage collector runs indefinitely, the destructor code does not run as soon as the variable loses scope. I understand that I can inherit from IDisposable and explicitly call Dispose on my object, but I was hoping there might be more connection problems, similar to how non.Net C ++ handles object destruction.
Desired Behavior (C #):
public class A {
~A { [some code I would like to run] }
}
public void SomeFreeFunction() {
SomeFreeSubFunction();
}
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();
}
}
source
share