Destructors

M

Mythran

Jimmy said:
Hi

when do you use destructors and what are the advantages /disadvantages?

ch Jim

Use destructors anytime you need to cleanup when the class gets destroyed.
Basically, you would implement the IDisposable interface's Dispose() method.
Normally, cleanup includes closing any open files, closing database
connections, cleaning up unmanaged resources, et cetera.

HTH,
Mythran
 
J

Jimmy

but what are the disadvantages if any?

ch Jim
Mythran said:
Use destructors anytime you need to cleanup when the class gets destroyed.
Basically, you would implement the IDisposable interface's Dispose() method.
Normally, cleanup includes closing any open files, closing database
connections, cleaning up unmanaged resources, et cetera.

HTH,
Mythran
 
D

Dave

Dispose is not a destructor.

A disadvantage of using a Destructor is that it does not allow for explicit clean-up of an object at runtime. The Dispose method is
a way of saying, "Hey, clean me up before you go!" to consuming classes. This allows for the explicit and timely release of
unmanaged resources such as Database connections and File references, etc. when the consuming classes no longer require the object
reference.

Once "Disposed", an object should be rendered unusable but it's up to the designer to explicitly throw an ObjectDisposedException
when members are accessed on a disposed custom class. You don't see this done too often :)

If you inherit from System.ComponentModel.Component, you receive a base implementation that prevents the GC (Garbage Collector) from
destroying your object without calling the virtual Dispose method first. This way, all of your cleanup code can be located in one
place. Neat.

I'm sure there are more disadvantages, but I can't think right now -- it's late.
 

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

Similar Threads


Top