Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is the difference between “dispose” and “finalize” variables in C#?

user-image
Question added by Mohammed Sufian Al-Omar , Software Development Division Mnanager , Arabian Food Supplies
Date Posted: 2017/05/04
sheejo absalone
by sheejo absalone , .net application developer (software engineer ) , wipro infotech

Dispose() Method: Dispose method will be used to free unmanaged resources like files, database connection etc. To clear unmanaged resources we need to write code manually to raise Dispose() method. This Dispose() method belongs to IDisposable interface.

 

Finalize() Method: This method also free unmanaged resources like database connections, files etc. It is automatically raised by garbage collection mechanism whenever the object goes out of scope.This method belongs to object class.

Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand Finalize() is used for the same purpose but it doesn't assure the garbage collection of an object.

Javed Ahmad
by Javed Ahmad , Senior Developer , HCL Technologies Ltd

Dispose() Method: Dispose method will be used to free unmanaged resources like files, database connection etc. To clear unmanaged resources we need to write code manually to raise Dispose() method. This Dispose() method belongs to IDisposable interface.

 

Finalize() Method: This method also free unmanaged resources like database connections, files etc. It is automatically raised by garbage collection mechanism whenever the object goes out of scope.This method belongs to object class.

Wael Inaim
by Wael Inaim , Manager of Information Technology Section. , Khatib & Alami

The finalizer is called when the GC detects that an object is eligible for collection. This happens at some undetermined period of time after the resource is not needed anymore. 

Dispose can be called even if other references to the object are alive.

Note that even when you provide explicit control using Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.

 

 

More Questions Like This