Tuesday, January 7, 2014

Destructor, Dispose, Finalize demo

namespace destructorCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Check c = new Check())
            {
                c.PrintAccess();
            }
        }
    }

    class Check : IDisposable
    {
        private bool IsDisposed = false;
        SqlConnection con;
        int check = 10;

        public Check()
        {
            con = new SqlConnection();
            check = 20;
        }

        ~Check()
        {
            CustomDispose(false);
        }

        public void PrintAccess()
        {
            Console.WriteLine("Print");
        }

        /// <summary>
        /// implemented dispose method from idisposable interface
        /// </summary>
        public void Dispose()
        {
            CustomDispose(true);
            //if not suppressed then automatically call destructor
            GC.SuppressFinalize(this);

            //this will only when you are using managed resources
            //as garbage collector only handles managed resources
            //managed resources - declared variables and objects
            //unmanaged resources - sql connection, opened file object etc.
            //for unmanaged resources do manual dispose, garbage collector will not do anything
            //GC.Collect();
        }

        private void CustomDispose(bool Disposing)
        {
            if (!IsDisposed)
            {
                if (Disposing)
                {
                    //Clean Up managed resources
                    if (con != null)
                    {
                        con.Dispose();
                    }
                }
                //Clean up unmanaged resources               
            }
            IsDisposed = true;
        }
    }
}

No comments:

Post a Comment