IDisposable pattern for C# objects

Hello everybody,

today I want to share my usage if IDisposable interface in C#.

Before code presentation some explanations:

1. If created by me class uses some unmanaged resources then it means that I should also implement IDisposable interface in order to clean memory. 
2. Clean objects as soon as I finished usage of it. 
3. In my dispose method I iterate over all IDisposable members of class and call Dispose.
4. In my Dispose method call GC.SuppressFinalize(this) in order to notify garbage collector that my object was already cleaned up. I do it because calling of GC is expensive operation.
5. As additional precaution I try to make possible calling of Dispose() multiple times.
6. Sometime I add private member _disposed and check in method calls did object was cleaned up. And if it was cleaned up then generate ObjectDisposedException 

public class SomeClass : IDisposable
        {
            /// <summary>
            /// As usually I don't care about it
            /// </summary>
            public void SomeMethod()
            {
                if (_disposed)
                    throw new ObjectDisposedException("SomeClass instance been disposed");
            }

            public void Dispose()
            {
                Dispose(true);
            }

            private bool _disposed;

            protected virtual void Dispose(bool disposing)
            {
                if (_disposed)
                    return;
                if (disposing)//we are in the first call
                {
                }
                _disposed = true;
            }
        }

No Comments

Add a Comment