Finalize and Dispose are the two methods provided by the .Net Framework for releasing the unmanaged resources like files, database connections etc.
Let us understand the difference between these two:
Finalize
Dispose
It is used to release unmanaged resources held by the object before that object is destroyed.
It is used to release unmanaged resources at any time.
It is called by the Garbage Collector and cannot be called by the User Code.
It is called by the User Code provided the Class implementing this method must implement the
IDisposable interface.
This method belongs to Object class.
This method belongs to IDisposable interface.
It effects the performance of the website as it is called by the Garbage Collector.
It does not show any effect to the performance of the website as it is called from the user
code.
This method is not suitable to free the object immediately. Example:
class employee
{
//This is the destructor of emp class
~employee()
{
}
//This destructor is implicitly compiled to the Finalize method.
}
This method can be used whenever we wan't to free the object. Example:
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
sqlcon.Close(); // close the connection
sqlcon.Dispose(); // detsroy the connection object
Note:SqlConnection class have built in implementaion of Dispose method
0 Comment(s)