Link to home
Start Free TrialLog in
Avatar of coder1313514512456
coder1313514512456Flag for United States of America

asked on

C sharp: Finalize() ~ instead of implementing IDisposable?

If I'm creating a class with network or database connections, why wouldn't I just clean them up inside a destrucotr ~SomeClass Finalize() method instead of having to be bothered with IDisposable and  Dispose()?

I've looked around a bit, but nowhere can I end up actually finding an answer to this simple question:
In C#, If I clean everything up in ~, isn't that acceptable?  Aren't I doing my duty?

Sorry to assign a high/urgent point value to this, but I'm trying to write something fairly quickly and need to sort this out.

Avatar of coder1313514512456
coder1313514512456
Flag of United States of America image

ASKER


The Title of this question is supposed to be:
"C#:  Finalize() ~ instead of implementing IDisposable?"

Not sure why it's being truncated by the number/pound/sharp sign and don't know how to change the Title.



ASKER CERTIFIED SOLUTION
Avatar of saragani
saragani

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks saragani.  Apparently I didn't try hard enough.  (And of course now I feel like a complete idiot!)
Yeah, that would be pretty much exactly what I was looking for.
But here's a question for you:  you would never have an object call Dispose() on itself, right?  Or are there cases?
 
Avatar of saragani
saragani

I don't understand the question. What exactly do you mean?

I'm not sure if that replies your question, but I for example never write a destructor (I was alway told to avoid ~ ) simple because when the object finally reaches the time when the GC is "killing" it, the destructor starts doing some stuff, preventing the object from being collected by the GC when it was intended to be collected.
(I think that in the links that I gave you they talk about it and say that it will take the GC to cycle to collect that object).

I usually don't have a Dispose function in my object. This is because I usually don't have special things that need to be closed or disposed.
However, there are small exceptions on that matter, for example when an object opens a file and closes it only when the object needs to die or sometimes when working with GDI.

Dispose was made for letting you close some handles and release objects when you think that you finished using that object (And you don't wanna wait for the GC to do that).