Implement a Disposable Class - CSharp Custom Type

CSharp examples for Custom Type:interface

Description

Implement a Disposable Class

Demo Code


using System;/* w w  w.j  a  v  a  2  s .  c om*/

    public class DisposeExample : IDisposable
    {
        bool isDisposed = false;
        private IntPtr resourceHandle;

        public DisposeExample()
        {
            resourceHandle = default(IntPtr);
        }

        ~DisposeExample()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                }

            }
            isDisposed = true;
        }

        public void SomeMethod()
        {
            if (isDisposed)
            {
                throw new ObjectDisposedException("DisposeExample");
            }
        }
    }

class MainClass
    {
        public static void Main()
        {
            using (DisposeExample d = new DisposeExample())
            {
                // Do something with d
            }

        }
    }

Related Tutorials