G
Guest
I believe that I fully understand the concepts behind IDisposable and
finalization (at least I hope I do) and I would like to get feedback from the
experts so that I can forward them on to others.
There are people who think that if a class implements IDisposable then it
should include a finalizer. What I told them was that you should only
include a finalizer if you have unmanaged resources you need to ensure are
cleaned up. Otherwise you should not include a finalizer whether or not you
implement IDisposable.
As an example of this case, the one where you might want to implement
IDisposable but do not need a finalizer, I said assume you have a class that
internally makes use of a FileStream object. It might open the object up at
some point during its lifetime and keep it open from then on. In this case
you might want to implement IDisposable to provide an explicit mechanism for
the caller to indicate they are done with your class. The implementation in
your class would simply call the FileStream's IDisposable.Dispose() method.
I argue that this class does not need a finalizer and in fact if this class
did include a finalizer it would be of no use. By the time the finalizer was
called you could not do anything with your FileStream instance as it may have
already been disposed (assuming you don't expose the instance outside your
class).
Is my statement/explanations valid?
finalization (at least I hope I do) and I would like to get feedback from the
experts so that I can forward them on to others.
There are people who think that if a class implements IDisposable then it
should include a finalizer. What I told them was that you should only
include a finalizer if you have unmanaged resources you need to ensure are
cleaned up. Otherwise you should not include a finalizer whether or not you
implement IDisposable.
As an example of this case, the one where you might want to implement
IDisposable but do not need a finalizer, I said assume you have a class that
internally makes use of a FileStream object. It might open the object up at
some point during its lifetime and keep it open from then on. In this case
you might want to implement IDisposable to provide an explicit mechanism for
the caller to indicate they are done with your class. The implementation in
your class would simply call the FileStream's IDisposable.Dispose() method.
I argue that this class does not need a finalizer and in fact if this class
did include a finalizer it would be of no use. By the time the finalizer was
called you could not do anything with your FileStream instance as it may have
already been disposed (assuming you don't expose the instance outside your
class).
Is my statement/explanations valid?