Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every user defined class need to implement IDisposable interface to get garbage collected

I am not sure how the user defined class objects are garbage collected. Do I need to implement IDisposable interface on every class and call the dispose() method on it to free the memory?

like image 535
kishore Avatar asked Aug 06 '10 20:08

kishore


2 Answers

No. Every normal managed .NET object gets garbage collected when you stop referring to it. IDisposable means that you you will implement a Dispose() method that needs to be called by the caller -- it usually releases things that aren't garbaged collected. It also helps with having a deterministic place to release memory.

Check out the IDisposable pattern to make sure you do it right:

http://www.atalasoft.com/cs/blogs/stevehawley/archive/2006/09/21/10887.aspx

like image 102
Lou Franco Avatar answered Sep 29 '22 00:09

Lou Franco


No, every object is disposed automatically.

IDisposable is usable when you have some kind of special operation to do at the object deconstruction. For example if you locks some resources like files or such during the work of your object, then you can release them in your Dispose method.

like image 37
Łukasz W. Avatar answered Sep 29 '22 00:09

Łukasz W.