is it ok to have empty destructor?
Loading
is it ok to have empty destructor?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Rajanikant HawaldarPosted Sep 13, 2022, 7:25 AM
When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.
Sachin SinghPosted Sep 14, 2022, 6:23 AM
Agreed with all, There is no need of destructor.
You can use the using block or can implement the finalize pattern if needed instead.
Vishal YelvePosted Sep 13, 2022, 2:29 PM
Hi Shaan,
Destructors are the techniques to remove instances of classes as soon as the class is closed. It is a very useful technique to clean memory and remove all the instances of the program. Using destructors you can release memory if your program is using the expensive external resource as files, images, etc.
Note: "You should not use empty destructor in the program. When you use destructor, an entry is created in Finalize queue. Therefore, when the destructor is called, the garbage collector is invoked to process the queue. If you have used an empty destructor, it causes unnecessary system performance issues."
When a Destructor is called it automatically invokes Finalize Method. Finalize method in C# is used for cleaning memory from unused objects and instances. So, when you call the destructor, it actually translates into the following code.
The programmer has no control over when the destructor will be executed because it is defined by the garbage collector. The garbage collector automatically checks for objects that are no longer referenced or are no longer being used by the application. When the garbage collector found such objects, it removes them automatically and frees up memory.
Actually, C# doesn’t require explicit memory management because the .Net Framework garbage collector automatically does it for you.
Uday DodiyaPosted Sep 13, 2022, 6:26 AM
Yes, that empty destructor is the same as the automatically-generated one. I've always just let the compiler generate them automatically; I don't think it's necessary to specify the destructor explicitly unless you need to do something unusual: make it virtual or private.
Refer Following Link For More
https://stackoverflow.com/questions/1025313/will-an-empty-constructor-or-destructor-do-the-same-thing-as-the-generated-one#:~:text=Since%20no%20destructor%20is%20defined,defining%20an%20empty%20destructor%2C%20ie.