The same we see people telling that dispose is not for nothign so use is. Do
you use every method forever in every class?
Of course we don't use all the methods of a class just because they're
there. That would be insane. But most methods of the class are to do with it
as an object - and Dispose() is different - because it's about managing the
resources the object consumes that the GC cannot/does not collect.
Cor says that the majority of objects inherit from the component model and
so get a Dispose() "for free" but don't actually need it.
Maybe so - but do we really know what is going on inside any object we
haven't written? In my opinion - no, we don't; I'd rather do defensive
programming and ensure that Dispose is called if its there.
That doesn't mean, necessarily, that I must explicitly call it. If the
object was added to my class by the designer, then I can trust that the
designer hooked up its Dispose. If I have written my own Dispose I should
call the Dispose on all the objects I allocate and reference as member
variables from within that method.
That leaves only objects, like Graphics, or Fonts, etc. that I allocate
within a function and whose scope is limited to that function. On these
objects I MUST call dispose before they go out of scope since there is no
other path for their dispose to be called
So the question remains: if an object exposes Dispose() when is it safe NOT
to call it? The corollary is: if an object exposes Dispose() can we assume
that there is a reason for it - i.e. that the object needs to be disposed or
the resource it represents will leak?
Since Dispose is about releasing memory (and resources) used by unmanaged
objects the GC WILL NOT do anything to clean them up - exactly because they
are unmanaged. So for such objects we MUST call Dispose to prevent leaks.
Also note - if you want to use Finalize to call Dispose for you for member
objects that must be disposed, remember that you need to write your Finalize
(the system can't do it for you!).
Chris