8.07.2012

DOTNET Framework Difference FAQs-2

1.Difference between Finalize() and Dispose() methods in .NET
S.No Finalize() Dispose()
1 Finalize() belongs to the Object class. Dispose() belongs to the IDisposable interface
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)
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
It is slower method and not suitable for instant disposing of the objects.

Example:

class employee
{
//This is the destructor of emp class
~employee()
{

}
//This destructor is implicitly compiled to the Finalize method.
}


Faster method for instant disposal of the objects.

Example: user interface Controls. Forms, SqlConnection class have built in implementaion of Dispose method.


4 It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory.
It is deterministic function as Dispose() method is explicitly called by the User Code.




2.Difference between Dispose and Destructor in .NET

S.No Dispose Destructor
1 Unmanaged resources are removed by dispose method and it is called manually It is used to release unused managed resources and it is called automatically by the Garbage Collector
2 It is used to remove the unused resources from the memory. It is used to de-allocate the allocated memory by the constructor method

3.Difference between Close() and Dispose() methods in .NET

S.No Close() Dispose()
1 When a Close() method is called,database connection will be temporarily closed and can be opened once again using Open() method.
Where as Dispose() method permanently close and removes connection object from memory and the resource no longer exists for any further processing.

Note: However, calling Dispose does not remove the connection from the connection pool.


Example:
try
{

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
}
catch
{
// code will be execute when error occurred in try block
}
finally
{
sqlcon.Close(); // close the connection
sqlcon.Dispose(); // desroy the connection object
}


Note: Only call the Close method on a Stream or a database connection if the object will be reused. Otherwise, use the Dispose method.

No comments:

Post a Comment