#StackBounty: #c# #object-oriented #design-patterns #.net #memory-management Implement IDisposable correctly using object composition p…

Bounty: 50

Is it possible to implement IDisposable pattern correctly while using object composition principle to promote code-reuse, reduce code duplication and hide verbose "official" implementation?

Rational

Proposal

Delegate the dispose logic to a dedicated class:

public class DisposeManager
{
    public Action Managed { get; set; }
    public Action Unmanaged { get; set; }

    protected virtual void Dispose(bool disposing)
    {
        // only dispose once
        if (disposed)
            return;

        if (disposing)
        {
            Managed?.Invoke();
        }

        Unmanaged?.Invoke();

        disposed = true; 
    }

    public void DisposeObject(object o)
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(o);
    }

    public void FinalizeObject()
    {
        Dispose(disposing: false);
    }

    private bool disposed;
}

Implement IDisposable in user class in the following way:

public class DisposeUser : IDisposable
{
    public DisposeUser()
    {
        // using lambda
        disposeManager.Managed = () =>
        {
            // [...]
        };

        // or using member method
        disposeManager.Unmanaged = DisposeUnmanaged;
    }

    ~DisposeUser()
    {
        disposeManager.FinalizeObject();
    }

    public void Dispose()
    {
        disposeManager.DisposeObject(this);
    }

    private void DisposeUnmanaged()
    {
        // [...]
    }

    private readonly DisposeManager disposeManager = new DisposeManager();
}

Benefits

  • much simpler to implement for user classes
  • more explicit (managed, unmanaged)
  • use composition
  • remove the needs for multiple base classes all implementing the dispose pattern and creating code duplication

Questions

  • Is it ever a good idea or more of a programmer fancy "improvement" idea ?
  • I’ve made a decent number of research on the dispose pattern and implementation but never found someone suggesting such idea, any reason why?
  • Any potential problems around hard refs, especially with Action capturing members, etc. that would prevent the actual user class to be collected correctly?
  • Other thought?

Thanks!


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.