Should class override Dispose(bool)
to just call a containing object Dispose()
?
Is it safe to have only Dispose()
method that calls a containing object Dispose()
like in example below?
public class DisposableContainer : IDisposable
{
private readonly IDisposable disposableObject = new();
public void Dispose()
=> disposableObject.Dispose();
}
What bad consequences of this way of implementation could be?
According to Microsoft documentation, if class overrides Dispose(bool disposing)
, disposableObject.Dispose()
should be called only when disposing
is true
. disposing
should be false
only when dispose called from a finalizer. But my class doesn not have finalizer.
Other questions about disposing in .NET on Stack Overflow are too general, just like the documentation. It seems like this simple specific case was not disscused yet.
Should I add boilerplate code like in the next example? Do I miss something to implement it properly?
public class DisposableContainer : IDisposable
{
private readonly IDisposable disposableObject = new();
public void Dispose()
=> Dispose(true);
protected virtual void Dispose(bool disposing)
{
if (disposing)
disposableObject.Dispose()
}
}