Finalize and Dispose in .Net Framework
.NET Framework provides two methods Finalize and Dispose for releasing unmanaged resources like files, database connections, COM etc. This article helps you to understand the difference between Finalize and Dispose method.
1. Finalize() belongs to the Object class.
2. It is automatically called by the Garbage Collection mechanism when the object goes out of the scope(usually at the end of the program
3. It is slower method and not suitable for instant disposing of the objects.
4. It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory.
//This is the destructor of emp class
//This destructor is implicitly compiled to the Finalize method.
1. Dispose() belongs to the IDisposable interface
2. We have to manually write the code to implement it(User Code)
ex: if we have emp class we have to inherit it from the IDisposable interface
and write code. We may have to suppress the Finalize method using GC.SuppressFinalize() method.
3. Faster method for instant disposal of the objects.
4. It is deterministic function as Dispose() method is explicitly called by the User Code.
user interface Controls. Forms, SqlConnection class have built in implementaion of Dispose method.
string constring = "Server=(local);Database=my; User Id=sa; Password=sa";
SqlConnection sqlcon = new SqlConnection(constring);
sqlcon.Open(); // here connection is open
// some code here which will be execute
// code will be execute when error occurred in try block
sqlcon.Close(); // close the connection
sqlcon.Dispose(); // detsroy the connection object
- There is performance costs associated with Finalize method
- There is no performance costs associated with Dispose method.
Dispose - Implement this when you are writing a custom class that will be used by other users.
Finalize - Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.
You cannot override the Finalize method in the C# or C++ languages. But you can override Finalize method in VB.NET since it does not support destructor.
You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically.
A Dispose method should call the GC.SuppressFinalize() method for the object of a class which 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.
Code Example :
// Using Dispose and Finalize method
public class MyClass : IDisposable
private bool disposed = false;
public void Dispose()
protected virtual void Dispose(bool disposing)
// TO DO: clean up managed objects
// TO DO: clean up unmanaged objects
disposed = true;
//At runtime C# destructor is automatically Converted to Finalize method