Why should we call SuppressFinalize when we dont have a destructor

Posted by somaraj on Stack Overflow See other posts from Stack Overflow or by somaraj
Published on 2010-04-09T06:14:11Z Indexed on 2010/04/09 6:23 UTC
Read the original article Hit count: 519

Filed under:

I have few Question for which I am not able to get a proper answer .

1) Why should we call SuppressFinalize in the Dispose function when we dont have a destructor .

2) Dispose and finalize are used for freeing resources before the object is garbage collected. Whether it is managed or unmanaged resource we need to free it , then why we need a condition inside the dispose funtion , saying pass 'true' when we call this overriden function from IDisposable:Dispose and pass false when called from a finalize.

See the below code i copied from net.

class Test : IDisposable
   {
     private bool isDisposed = false;

     ~Test()
     {
       Dispose(false);
     }

     protected void Dispose(bool disposing)
     {
       if (disposing)
       {
         // Code to dispose the managed resources of the class
       }
       // Code to dispose the un-managed resources of the class

       isDisposed = true;
     }

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

what if I remove the boolean protected Dispose function and implement the as below.

   class Test : IDisposable
   {
     private bool isDisposed = false;

     ~Test()
     {
       Dispose();
     }


     public void Dispose()
     {
      // Code to dispose the managed resources of the class
      // Code to dispose the un-managed resources of the class
      isDisposed = true;

      // Call this since we have a destructor . what if , if we dont have one 
       GC.SuppressFinalize(this);
     }
   }       

© Stack Overflow or respective owner

Related posts about .NET