Suppose that I have the following classes:
class Foo : IDisposable
{
public void Dispose()
{
bar.Dispose();
}
private Bar bar = new Bar();
}
class Bar : IDisposable
{
public void Dispose()
{
baz.Dispose();
}
private SomeThirdPartyLibraryClass baz = new SomeThirdPartyLibraryClass();
}
This code works well when using using
statement:
using (Foo foo = new Foo())
{
// ...
}
// All resources should be disposed at this time
However, if for some reason user of this class forgot to use using
statement, resources will never be disposed.
According to MSDN, I should implement disposable pattern in the following manner:
class Foo : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing) {
// Free any managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~Foo()
{
Dispose(false);
}
bool disposed = false;
private Bar bar = new Bar();
}
(the same goes for Bar
)
But where exactly should I place bar.Dispose();
and baz.Dispose();
code?
Should it be under "managed cleanup" section or under "unmanaged cleanup" section?
As the name suggests, I don't know the implementation of SomeThirdPartyLibraryClass
(and anyway, it can be changed over time).
What should I do then?