tags:

views:

72

answers:

3

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();
    }
}
+4  A: 

The using keyword with an object implementing IDisposable does just that.

For instance:

using(FileStream stream = new FileStream("string", FileMode.Open))
{
    // Some code
}

This is replaced by the compiler to:

FileStream stream = new FileStream("string", FileMode.Open);
try
{
    // Some code
}
finally
{
    stream.Dispose();
}
Coincoin
+8  A: 

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.

Philippe Leybaert
(+1) Good to note that "using" is shorthand for utilizing the Dispose method and specifically not for utilizing the destructor and removing the object from memory.
Matt Hamsmith
+3  A: 

Unfortunately, no.

Your best option is to implement IDisposable with the IDisposable pattern.

Lasse V. Karlsen
See also http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae
TrueWill