c# – Difference between Dispose, Finalize, Destructor and GC class

Question:

I tried my luck on google on this topic and finally froze.

  1. I'll start with GC – earlier in Shildt I read that you cannot call the garbage collector, that it is automatically launched by the environment itself and there is nothing you can do about it, but I found such a GC.Collect() method, which, according to the description, launches the garbage collector. And the GC class itself also allows you to manage it. So all the same it turns out that it can be called manually? Or are there some subtleties and nuances?

  2. Enlighten what is actually the difference between Dispose и Finalize ? Which of these works with managed and what with unmanaged resources? And what is the essence of the implementation of the IDisposable interface (after all, in fact, everything can be done in the destructor)? As I understand it, the destructor and Dispose do the same thing. If not, then what does the destructor do (I read earlier that the destructor describes the steps that the program should take when destroying an object, but Dispose does the same in essence).

  3. From all of the above, it becomes completely unclear what Finalize does then. Please explain.

Answer:

  1. Can. But it is rarely needed.
  2. They have little in common at all. Dispose is needed to release resources "here and now" (not quite so in fact. Calling Dispose signals that you want to release the resource, but not the fact that this will necessarily happen right there). The necessity and advantage of the IDisposable interface is precisely that its implementation allows you to release resources not when the garbage collector gets to them, but when the programmer needs it. Resources can be expensive, and keeping them in memory indefinitely can be wasteful. There are no destructors in C # at all. There are finalizers. The difference is that the timing of the finalizer call is undefined. It is also worth noting that if Dispose is intended to be called manually, then the finalizer cannot be called manually. This is done automatically.
  3. Finalize is executed before the object is destroyed. We can say that this is the "last chance" to free resources correctly. You can also think of Finalize as the "last will of a dying" object. It only makes sense to define this method if the class has access to some unmanaged resource.
Scroll to Top