Can a virtual method be called in a C# destructor

R

Robert

I'm reading the book "Programming .NET Components" by Juval Lowy, a renowned
..NET expert as recognized by MSFT. In the book he provides a base class
example that implements a pattern for safely cleaning up your objects
(handling "IDisposable", etc.). His class calls a (do-nothing) virtual
"Cleanup()" function from its destructor however (we're supposed to override
it) and I'd like to confirm that this is in fact safe. Presumably it is but
it's not in C++ for good reason (since objects are destroyed from the
bottom-up). This would make sense in any language but I've read elsewhere
that virtual methods aren't illegal in C# constructors (though their safety
is another matter). Can anyone comment on this situation in particular. Is
it safe to call a virtual "Cleanup()" function from a base class destructor.
Thanks.
 
R

Robert

In C# I they are called Finalizers, not Destructors.
That is safe because the garbage collector takes two passes to collect
an object with a finalizer. The first pass calls the finalizer, and
the second pass collects the object.

More on finalizers:
http://dn.codegear.com/article/29365#CSharpFinalizers

Thanks for the info. After further reading I discovered that a C# destructor
is simply a glorified (exception-handling) wrapper around "Finalize()". I'll
take a detailed look at the link you provided however. It looks very
informative. Thanks again.
 
S

Samuel R. Neff

With a normal IDisposable implementation finalizers call a virtual
Dispose method, so yes you can call virtual methods.

Just remember that a finalizer can not reference other managed objects
('cause objects can be gc'd out of order) and this can be easy to
forget if your finalizer calls other methods, especially if that kicks
off some other call chain. That's one of the advantages of the
Dispose pattern, everyone knows what dispose is and what context it's
being called in (based on the disposing parameter) and should avoid
referencing managed objects when disposing is true.

HTH,

Sam
 

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