Sumitra Paul

Sumitra Paul

  • NA
  • 51
  • 33.7k

Dispose pattern?

Sep 4 2012 6:19 AM

Hi,

I was going through dispose pattern. I implemented IDisposable inteface with few codes and tried to dispose some object.
But not sure how the dispose method gets called.

Please find my code below:

public class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.TestMethod();
        }
    }

    public class MyClass : IDisposable
    {
        StreamReader strReader;
        private bool disposed = false;
        public void TestMethod()
        {
            strReader = new StreamReader("TextFile1.txt");
        }
        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    if (strReader != null)
                    {
                        strReader.Dispose();
                    }
                }
                disposed = true;
            }
        }

        #endregion
    }


Now here, from where to call dispose method ?

Is that correct the way I am doing?
Is it that for each object that i create, I need to dispose it this way?

Thanks.


Answers (5)