Destructors

  • Thread starter Thread starter Jimmy
  • Start date Start date
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
 
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
 
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.
 
Back
Top