Microsoft design guidelines mention Dispose pattern and scenarios how to use it:
DO implement the Basic Dispose Pattern on types containing instances of disposable types. See the Basic Dispose Pattern section for details on the basic pattern.
Later, they show the Basic Dispose Pattern as follows:
public class DisposableResourceHolder : IDisposable {
private SafeHandle resource; // handle to a resource
public DisposableResourceHolder(){
this.resource = ... // allocates the resource
}
public void Dispose(){
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing){
if (disposing){
if (resource!= null) resource.Dispose();
}
}
}
My questions are:
- Why do we need to implement Dispose(bool) if it has just a single call with parameter true? It could be easily simplified to just parameterless
Dispose() {resource?.Dispose();}
. Note we don't need finalizer here because objects we are referencing are managed and have their own finalizers, so they won't be leaked. - Why do they recommend to call
GC.SuppressFinalize(this)
while not having finalizer? GC anyway wouldn't call finalizer because it does not exist! - The only case when I see the need of Dispose(bool) is when we really have some unmanaged references, which does not implement IDisposable nor finalizer (like shown in this article). But then the meaning of
bool disposing
would bebool includingManagedResources
. So why is it named so misleading 'disposing' to what it should do in fact?