C# IDisposable pattern - private disposed flag

54 views Asked by At

https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose

I'm wondering why each derived class has its own private _disposedValue flag. What if there is just one flag in base class, and also calling base.Dispose(disposing) is done inside if (!IsDisposed)

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

public class BaseClassWithSafeHandle : IDisposable
{
    // To detect redundant calls
    protected bool IsDisposed { get; private set; }

    // Instantiate a SafeHandle instance.
    private SafeHandle? _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Public implementation of Dispose pattern callable by consumers.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (!IsDisposed)
        {
            if (disposing)
            {
                _safeHandle?.Dispose();
                _safeHandle = null;
            }

            IsDisposed = true;
        }
    }
}

using System;

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

public class DerivedClassWithSafeHandle : BaseClassWithSafeHandle
{
    // Instantiate a SafeHandle instance.
    private SafeHandle? _safeHandle = new SafeFileHandle(IntPtr.Zero, true);

    // Protected implementation of Dispose pattern.
    protected override void Dispose(bool disposing)
    {
        if (!IsDisposed)
        {
            if (disposing)
            {
                _safeHandle?.Dispose();
                _safeHandle = null;
            }

            // Call base class implementation.
            base.Dispose(disposing);
        }
    }
}

there is some discussion here In an IDisposable pattern should a base class allow derived classes to share its disposed flag?

but my proposal is that derived class would not be able to set the flag.

this is just a question about recommendation from Microsoft

0

There are 0 answers