0

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()
    }
}
Daniil Palii
  • 975
  • 9
  • 21
  • 4
    Having a `Dispose(bool disposing)` is to facilitate derived classes, that might introduce unmanaged resources that need to be finalized. It has nothing to do with what disposable objects your base class holds. You can use a "simple" implementation of `Dispose` (with no overload) if you make your class `sealed`, as then this scenario is excluded. – Jeroen Mostert Jul 06 '22 at 11:36
  • Does this answer your question? [Use of Finalize/Dispose method in C#](https://stackoverflow.com/questions/898828/use-of-finalize-dispose-method-in-c-sharp) – GSerg Jul 06 '22 at 11:37
  • 2
    It is not safe. A key property of Dispose(bool) is that it is `virtual`. So the type of the object reference does not matter when the client code starts disposing. That it is not the actual type of the object but a less-derived type is quite common. The virtual keyword ensures that it always starts at the most-derived class type. And when it calls base.Dispose() then the less-derived type gets a chance to cleanup, repeatedly as needed to walk the hierarchy. – Hans Passant Jul 06 '22 at 11:49
  • @JeroenMostert, add it as answer and I will vote for it – Daniil Palii Jul 06 '22 at 12:32

0 Answers0