GARBAGE COLLECTOR VS IDISPOSABLE INTERFACE IN C#

GARBAGE COLLECTOR

IF a object is no longer used, Garbage collector releases the memory to the managed objects..

IDISPOSABLE INTERFACE ;

But  IDISPOSABLE  INTERFACE  releases unmanaged objects.



Implementing Dispose


public class MyClass : IDisposable
{
   private TextReader reader;
   private bool disposed = false; // to detect redundant calls
   public MyClass()
   {
       this.reader = new TextReader();
   }

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

           disposed = true;
       }
   }

   public void Dispose()
   {
       Dispose(true);
       GC.SuppressFinalize(this);
   }
}

Comments