Destructor vs IDisposable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Destructor vs IDisposable

What's the difference between destructor and an implementation of the dispose method of the IDisposable?

8th Nov 2016, 2:39 PM
Hernane Orlando
Hernane Orlando - avatar
4 Answers
+ 4
a destructor disposes of an instance of a class/wipes it from memory, whereas idisposible is an interface that classes inherit from that allows the class to use methods like dispose. this means u you can manually dispose of an instance without waiting for gc/garbage collector to destroy it
10th Nov 2016, 6:12 PM
Akinni James
Akinni James - avatar
+ 2
Michael, you can not manually invoke a deconstructor
11th Nov 2016, 12:48 AM
Akinni James
Akinni James - avatar
+ 1
Implementing IDisposable the object can be instructed to immediatelly get rid of UNMANAGED resources like file handles, database connections, (large) images, etc. even far in advance to a garbage collection. Garbage collection won't destruct the object until there is no reference to it anymore. Furthermore, garbage collection does not run at predefined periodic times. It might run at some time in the future if there is nothing better to do. Using a destructor in C# makes this even worse, because such obects are only marked to be collected in the first GC run while disposing unmanaged resources might be invoked through IDisposable. Then in the second later run of the GC the managed obect is destructed. Therefore destructors should not be used in C#. Besides, implementing IDisposable enables using the syntax sugar of using() { }.
14th Mar 2018, 10:26 PM
Konrad
0
It depends on what resources you are releasing. A destructor is useful when you are done with unmanaged objects and you want to free up the memory, the Garbage Collector is not responsible for cleaning these objects up you are. Edit: for clarification your destructor is called by the Garbage Collector when it determines your object is no longer being used or you manually invoke garbage collection. IDisposable is useful for ensuring connections are closed and class level objects which can be disposed of are. Your implementation of IDisposable should be called by your destructor.
10th Nov 2016, 11:54 PM
Michael Dolence