Essential C# IDisposable interface  Suggest an edit

In a class with managed and unmanaged resources

It’s important to let finalization ignore managed resources. The finalizer runs on another thread – it’s possible that the managed objects don’t exist anymore by the time the finalizer runs. Implementing a protected Dispose(bool) method is a common practice to ensure managed resources do not have their Dispose method called from a finalizer.

public class ManagedAndUnmanagedObject : IDisposable
{
    private SqlConnection sqlConnection = new SqlConnection();
    private UnmanagedHandle unmanagedHandle = Win32.SomeUnmanagedResource();
    private bool disposed;

    public void Dispose()
    {
        Dispose(true); // client called dispose
        GC.SuppressFinalize(this); // tell the GC to not execute the Finalizer
    }

    protected virtual void Dispose(bool disposeManaged)
    {
        if (!disposed)
        {
            if (disposeManaged)
            {
                if (sqlConnection != null)
                {
                    sqlConnection.Dispose();
                }
            }

            unmanagedHandle.Release();

            disposed = true;
        }
    }

    ~ManagedAndUnmanagedObject()
    {
        Dispose(false);
    }
}


Table Of Contents
22 Enum
25 GUID
61 IDisposable interface
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close