Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDisposable Interface

Tags:

c#

I know about IDisposable Interface and it's use in .net but there is a question in my mind that If i am writing all managed code , does implementing IDisposable interface make any sense?

i know when and how to use Idisposible but my question is if i am writing all managed code say a simple class nothing expensive in it so if i implement IDisposable in this class and do some cleanup like freeing some global values, Does it make some sense?

like image 590
TalentTuner Avatar asked Oct 11 '10 17:10

TalentTuner


Video Answer


1 Answers

No, you may not need to use IDisposble interface. However, it's recommended under certain circumstances (I might add later more as I remember :) ):

  1. You class has many objects and there are of lots of cross references. Even though its all managed, GC may not be able to reclaim the memory due to alive references. You get a chance (other than writing a finalizer) to untangle the references and break up the links the way you attached them. Hence, you are helping the GC to reclaim the memory.

  2. You have some streams open which are alive till the object of the class dies. Even though such implementations of files/network etc are managed, they go deep down to handles in Win32 mode. Hence, you get a chance to write a Dispose method where you can close the streams. The same is true for GDI objects, and some more.

  3. You are writing a class which uses unmanaged resources, and you want to ship your assembly to third parties. You better use disposable pattern to make sure you are able to free the handles to avoid the leakage.

  4. Thanks to supercat for this: Your class implements lots of event handlers and hooks them up to events. The objects of classes which expose the events, like Form etc., will not be freed up by GC since the implementations local to your class (maybe) are still hooked into those events. You can unhook those event handlers in Dispose; again helping GC.

Hmm... I can't remember more right now, but if the class is complex in its behaviours, you might want to rethink why you don't want implement IDisposable interface.

like image 159
Nayan Avatar answered Oct 13 '22 23:10

Nayan