0
Answer

Destructor vs finalize vs dispose

amit_gupta14

amit_gupta14

15y
8.6k
1

Please respond for the following scenarios:
1. Destructor internally calls finalize(). We donot explicitly mention finalize() in the code. Am I right?
2. Destructor is handled by CLR. Does CLR also handles dispose?
3. Give examples of managed, unmanaged resources. I have seen the statement that GC(part of CLR) handles unmanaged resources.
Does it mean GC only handles unamanged resources, why not managed?
If yes, then who handles managed resources?
4. If dispose can be called at our own, then why do we need destructor? Any case where we should use dispose or destructor?
5. Destructor impacts performances. Dispose also?
6. If we have mentioned both destructor as well as dispose for same object and written same code, which is executed 1st?
Moreover, will both be executed one after another? If yes, how to stop it?
7.Keep in mind you should call GC.SuppressFinalize(this); in your dispose method to tell the GC that the object was manually disposed and shouldn't be finalized. I have read this statement. Is it applicable only when we use destructor and dispose both or always required irrespecive of use of destrcutor?

8.Since .NET has a garbage collector why do we need finalizers/destructors/dispose-pattern?
If I understand correctly the .net runtime will always clean up after me. So if I create new objects and I stop referencing them in my code, the runtime will clean up those objects and free the memory they occupied.
Since this is the case why then do some objects need to have a destructor or dispose method? Won't the runtime clean up after them when they are not referenced anymore?
9. Finalize() is called implicitly when Destructor is used, is it true?
Suppose we donot use destructor, still finalize() will be called by GC?
10. Finalize only handles managed resources, dispose handles only unmanaged, right?