I've read carefully through this article and it seems to clearly state that the dispose pattern should be implemented in all cases of IDisposable
implementation. I'm trying to understand why I need to implement the dispose pattern in cases when my class holds only managed resources (i.e. other IDisposable
members or safe handles). Why cannot I just write
class Foo : IDisposable
{
IDisposable boo;
void Dispose()
{
boo?.Dispose();
}
}
If it's definitely known that there are no unmanaged resources and there is no point to call Dispose
method from finalizer as managed resources aren't being freed from finalizer?
Update: In order to add some clarity. The discussion seems to come down to the question whether it's needed to implement the dispose pattern for every base public non-sealed class which implements IDisposable
or not. I however cannot find potential problems with hierarchy when a base class without unmanaged resources doesn't use dispose pattern while child classes which have unmanaged resources do use this pattern:
class Foo : IDisposable
{
IDisposable boo;
public virtual void Dispose()
{
boo?.Dispose();
}
}
// child class which holds umanaged resources and implements dispose pattern
class Bar : Foo
{
bool disposed;
IntPtr unmanagedResource = IntPtr.Zero;
~Bar()
{
Dispose(false);
}
public override void Dispose()
{
base.Dispose();
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
//
}
// close handle
disposed = true;
}
}
// another child class which doesn't hold unmanaged resources and merely uses Dispose
class Far : Foo
{
private IDisposable anotherDisposable;
public override void Dispose()
{
base.Dispose();
anotherDisposable?.Dispose();
}
}
Even more, for me it looks as better separation of concerns when implementations are responsible only for those things which they are aware of.
You should implement this pattern for all base classes that implement Dispose() and are not sealed
. – DiazA
,B : A
,C : B
andConsole.WriteLine
everywhere. As I believe that when literature seems contradictory, it's always easier to try yourself. – LoadstarYou should implement this pattern for all base classes that implement Dispose() and are not sealed
, taken from there. – Diaz