Differences between destructor, deletion, and method termination

I am learning how the garbage collector works in C #. I am confused about using Destructor , Dispose and Finalize methods.

According to my research and understanding, the Destructor method in my class will tell the garbage collector to collect garbage in the manner specified in the destructor method, which cannot be explicitly called in class instances.

The Dispose method is designed to provide the user with the ability to control garbage collection. The Finalize method frees the resources used by the class, but not the object itself.

I am not sure if I understand correctly. Please clarify doubts. Any additional links or manuals are appreciated.

+51
c # destructor dispose finalize
Dec 21 '12 at 10:25
source share
2 answers

The destructor implicitly calls the Finalize method, they are technically the same. Dispose is available with the object that implements the IDisposable interface.

You Can See: C # Destructors - MSDN

The destructor implicitly calls Finalize on the base class of the object.

An example from the same link:

 class Car { ~Car() // destructor { // cleanup statements... } } 

Destructor code is implicitly translated into the following code:

 protected override void Finalize() { try { // Cleanup statements... } finally { base.Finalize(); } } 

Your understanding of the destructor is true:

From MSDN

The programmer has no control over the call to the destructor, because it is determined by the garbage collector . The garbage collector scans objects that are no longer used by the application. If it considers an object that has the right to destroy, it calls the destructor (if any) and restores the memory used to store the object. Destructors are also called when a program exits. You can force garbage collection by calling Collect, but you should avoid this most of the time, as this can cause performance problems.

+48
Dec 21 '12 at 10:27
source share

In C # terms, the destructor and finalizer are basically interchangeable concepts and should be used to release unmanaged resources when collecting a type, such as external handles. Rarely what you need to write a finalizer.

The problem is that the GC is not deterministic, so the Dispose() method (through IDisposable ) allows for deterministic cleanup. This is not related to garbage collection and allows the caller to free up any resources sooner. It is also suitable for use with managed resources (in addition to unmanaged resources), for example, if you have a type that encapsulates (say) a database connection, you might want to get rid of this type to free the connection.

+36
Dec 21 '12 at 10:31
source share



All Articles