Difference between Destructor, Dispose and Finalize

Destructor
They are special method that contains clean up code for the object.We can't call them explicitly in our code as they are implicitly called by GC(Garbage Collector).In c# they have same name as the class name preceded by the "~" sign.
class MyClass
    {
        public MyClass()
        { }

        ~MyClass()
        { }

    }

Dispose
These are like any other methods in the class and can be called explicitly but they have a special purpose of cleaning up the object.In the dispose method we write clean up code for the object.It is important that we freed up all the unmanaged resources in the dispose method like database connections,files, etc..
The class implementing dispose method should implement IDisposable which is inherited by interface and it contains GC.SupressFinalize() method for the object it is disposing if the class has destructor because it has already done the work to clean up the object ,then it is not necessary for the garbage collector to call the object's finalize method .

  • Dispose is called by the user.
  • Same purpose as finalize to free unmanaged resources.However implement this when you are writing a custom class that will be used by other users.
  • Overriding Dispose() provides a way for the user code to free the unmanaged objects in our custom class.
  • Dispose method can be invoked only by the classes that IDisposable interface.
Finalize
Finalize is called by Garbage Collector implicitly to free unmanaged resources.The garbage collector calls this method at some point after there are no longer valid references to the object.There are some resources like windows handler,database connection which cannot be collected by the garbage collector.Therefore the programmer needs to call Dispose() method of IDisposable interface.
  • Implement it when we have unmanaged resources in our code and want to make sure that these resources are freed  when the garbage collection happens.
  • Finalizer should always be protected not public or private so that the method cannot be called from the applications code directly and at the same time it can make a call to the base Finalize method
  • Finalize should release unmanaged resources only.



Comments

Popular posts from this blog

Enable HTTP Transport Security (HSTS) in IIS 7

When to use Truncate and Delete Command in SQL

Extension Class in C#