3

I need some clarification on…

  1. … how the CLR — more specifically, the garbage collector — finds the classes which implement the IDisposable interface; and

  2. … how it calls the Dispose method (of all classes which implement the IDisposable interface) to free up memory?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Syed
  • 931
  • 13
  • 28
  • 3
    I think you should read a bit more about IDisposable, see http://stackoverflow.com/questions/12368/how-to-dispose-a-class-in-net - IDisposable has nothing to do with freeing up memory, nor does GC run it at all. Also see http://stackoverflow.com/questions/732864/finalize-vs-dispose – Lasse V. Karlsen Aug 09 '11 at 13:56
  • @Lasse V. Karlsen: Thanks for links – Syed Aug 09 '11 at 14:42

2 Answers2

4

The CLR does not call Dispose(), this is up to user code to call either directly or through the use of the using statement. The CLR will however call finalizers, although this is not gauranteed.

Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
1

Dispose is not called automatically. The compiler generates calls to Dispose when you write using, or call Dispose directly.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • In this case why we need to implement IDisposable method, instead we can create any method which will free the resource. Even 'using' also expanding with try...finally() where it calls Dispose method. We can also do the same without implementing IDisposable interface. The answer for this will explain the need of interface I guess. – Syed Aug 09 '11 at 17:24
  • @Syed I don't understand that comment. – David Heffernan Aug 09 '11 at 17:25
  • From your answer what I'm understanding is we need to explicitly call the Dispose method. My doubt is, then why we need to implement IDisposable interface and then Dispose method, we can directly write any other method which is freeing the resource. – Syed Aug 09 '11 at 17:38
  • @Syed You are at liberty to write your own method, named however you like, and call it to free the resource. However, you will miss out on a number of important features, not least the ability to write `using`. – David Heffernan Aug 09 '11 at 17:39
  • I agreed sir, then my point is why we need interfaces. I think I am missing something. Even 'using' also expanding to try...finally() block and in finally block it is calling Dispose method. – Syed Aug 09 '11 at 17:43
  • The design uses interfaces because that is the natural way to allow classes to implement optional functionality. Think about an alternative and see if you can find a better one? – David Heffernan Aug 09 '11 at 17:48
  • @DavidHeffernan let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/2290/discussion-between-syed-and-david-heffernan) – Syed Aug 09 '11 at 17:51