Click here to Skip to main content
15,860,844 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
This is one of the interview questions... can we call dispose method inside finalize method because finalize() is called automatically by the Garbage Collector, so can we all dispose in finalize.
What's the difference between dispose and finalize?
Posted
Updated 24-Aug-10 8:13am
v3

You should consider that telling you the answer to this interview question will not raise your overall experience to the level that will get you a job.

Dispose is something you can call yourself. Finalise calls it for you if you failed to call it. Thus, the dispose method is used to give us control over cleaning up of resources.
 
Share this answer
 
v2
Comments
Mastermanoj 24-Aug-10 13:51pm    
Yes Christian thanks a lot,but i am trying to raise my level.
we call dispose when we want.but if we are calling it inside finalize method then what happens since both does the cleaning of resources and finalize is called when garbage collector starts cleaning up of resource.
1. Dispose is part of IDisposable interface and is called explicitly by invoking method Dispose or by "using" statement, which calls it automatically.

2. There is an article about it on MSDN:
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx[^].
 
Share this answer
 
v2
Yes, we can call dispose method in Finalize().

By doing this, we force the dispose method to be called automatically.

We can call the dispose method in Finalize() and in Dispose method, suppress the finalize method using GC.SuppressFinalize.

Below is the sample code of the pattern. This is the best way we do clean our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector twice. It will suppress the finalize method thus avoiding the two trips.

VB
Public Class ClsTesting
  Implements IDisposable
    Public Overloads Sub Dispose()Implements IDisposable.Dispose
      ' write ytour clean up code here
        GC.SuppressFinalize(Me)
    End Sub
    Protected Overrides Sub Finalize()
       Dispose()
    End Sub
 End Class


Hope this may help you. :)
 
Share this answer
 
v3
Comments
Sandeep Mewara 24-Aug-10 12:07pm    
Just formatted the code part.
Mastermanoj 24-Aug-10 13:56pm    
Thanks a lot Sandesh,this has cleared my some of doubts.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900