tags:

views:

110

answers:

7

In .NET, is there a simple way for a class to be notified as it falls out of scope?

+1  A: 

If it implements IDisposable and you're using a using block, sure.

Welbog
+3  A: 

No.

If you need to clean up resources other than memory, implement IDisposable and create your objects with using blocks. If you need to clean up memory, you really can leave it to the garbage collector.

Joel Coehoorn
A: 

No there isn't.

Joe
A: 

No, there is no deterministic finalization in any .NET language. The garbage collector is responsible for finalizing objects that have no roots in the application.

Andrew Hare
He wasn't asking about finalization though, he was asking about being notified. And as for it not being available in any .NET language, if you program in C++/CLI (the successor to Managed C++ which first appeared in VS2005), you can declare a reference to an object as if it were an auto variable. If that object's class implements IDisposable it will be notified when it goes out of scope. This is a feature sadly missing from C# IMHO.
U62
btw. wasn't me that downvoted!
U62
A: 

If it implements IDisposable, your Dispose() method would find out:

using (var c = new YourClassImplementsIDisposable() )
{
    // Stuff happens
}
// c.Dispose has been called

otherwise no, because your object is just 'hanging out' until GC

n8wrl
A: 

You could use a finalizer. It would be called once garbage colelcted, but not immediately after leaving scope.

http://www.switchonthecode.com/tutorials/csharp-tutorial-object-finalizers

Charles
+1  A: 

Yes, with some languages. C++/CLI will emit Dipose calls for IDisposable implementers when their non-heap allocations drop out of scope (effectively giving them the same semantics as stack allocated resource in normal C++). Moreover, C++/CLI destructor syntax of ~Classname becomes an implementation of Dispose (and makes the class implement IDisposable).

I would expect other languages with traditional deterministic destruction to adopt this policy as time goes on. As others have mentioned, you can emulate it in C# with "using", but it's not quite the same.

Adam Wright