mick said:
[...]
Just for clarity then (for me) Do I need
to Dispose of this oject myself or does the GC do it for me? I also remember
watching one of those MSN Webcast series which, again, I`m almost certain
said that if you`re not sure which objects you should dispose of yourself
then check to see if it exposes the Dispose method.
What you should check for is IDisposable. For example:
object someObject = ...;
later:
IDisposable disposable = someObject as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
How exactly that code will look depends a lot on the lifetime of the
object. If it's used only locally, then a "using" statement is best.
Otherwise, you need to track the lifetime of the object in some sensible
way, and make sure you call Dispose() before you lose track of the object.
Note that in many cases, you know the exact type of the object, and thus
already know whether it implements IDisposable or not, and thus can just
go ahead and call Dispose() directly, without checking for the
implementation (for some objects – those that implement IDisposable
explicitly rather than implicitly – you'll have to cast them to
IDisposable to access the Dispose() method).
In any case, the phrase "when you are finished with it" hides a lot of
potential complexity. In the SoundPlayer example, it's reasonable to
assume that you might want to pre-load a sound, and then keep that
pre-loaded SoundPlayer instance around so that you can play the sound
any time you like. In that case, you wouldn't dispose the instance
until you are sure you won't need to play that sound again. That might
actually be when your program is shutting down!
In any case, yes…you should always dispose your objects somehow. And
that's true even if you happen to find out that for a particular object,
the Dispose() method turns out to be a NOP. You never know when the
object implementation might change. If it implements IDisposable,
that's its way of telling you that you do need to dispose it when you're
finally through with it.
Properly implemented IDisposable objects will also have a finalizer,
which will allow the GC to dispose the object for you if you should
happen to forget _and_ the object becomes unreachable (i.e.
collectable). But you shouldn't rely on that; it's a backstop for the
object, not for your own code to depend on. Garbage collection and
object finalization happens on a non-deterministic basis; even if the
object does get finalized, it's less efficient to let the GC finalize
objects than to dispose them explicitly. And there is actually no
guarantee the GC will ever actually dispose and collect your object.