How can I write a method that is called when an object goes out of scope?

P

Paul Wilkinson

How can I write a method that is called when an object goes out of
scope? I've looked all over, so far I've only found discussions of how
to write methods that don't = )
 
C

cody

You cannot, because .NET uses like java a nondeterministic garbage
collector, which means the system does *not* know when exactly your objects
are go out of scope. It inspects sometimes all objects if they are still
reachable, and sweep away the rest.
But you can provide a finalizer (a destructor in C#) which will be called
when an object is *collected*. Though there are some things pay attention to
and you should rarely use finalizer as they affect negatively your programs
performance.
 
J

Jon Skeet [C# MVP]

Paul Wilkinson said:
How can I write a method that is called when an object goes out of
scope? I've looked all over, so far I've only found discussions of how
to write methods that don't = )

Objects don't go out of scope - variables do.

You can write a finalizer which will be called before the object is
garbage collected, but that will happen at some time after the object
is no longer referenced. It may not even happen at all.

Why do you need to do this? If it's for resource clean-up, you should
implement the IDispoable interface.
 
S

Sam Jost

Paul Wilkinson said:
How can I write a method that is called when an object goes out of
scope? I've looked all over, so far I've only found discussions of how
to write methods that don't = )

Look up the using() command and the IDisposable pattern.

With these you will get a call when the object leaves the using()-scope, and
it is even exception-save.

Sam
 
D

Daniel O'Connell [C# MVP]

Jon Skeet said:
Objects don't go out of scope - variables do.

You can write a finalizer which will be called before the object is
garbage collected, but that will happen at some time after the object
is no longer referenced. It may not even happen at all.

Why do you need to do this? If it's for resource clean-up, you should
implement the IDispoable interface.

Just a clarification: implementing IDisposable will not automatically cause
any sort of call when a variable goes out of scope or an object is
collected(unless there is a finalizer of course). It is just a standard
pattern which you should use and call manually, usually by using the using
statement.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top