In .NET, is there a simple way for a class to be notified as it falls out of scope?
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.
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.
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
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
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.