I am little bit confused about use of destructor in c#. In my knowledge we can't call destructor acording to my wish it will call automatically before garbage collector for performing some work over class (object) so i want to ask if we are using destructor in c# then whe we need to garbage collector. As i know that destructor can take care of memory then why we need to garbage collector ?
In object-oriented programming, a destructor gives an object a last chance to clean up any memory it allocated or perform any other tasks that must be completed before the object is destroyed. Like constructors, destructors are defined as subroutines in the class definition.
Destructors in C++ Destructor is also a special member function like constructor. Destructor destroys the class objects created by constructor. Destructor has the same name as their class name preceded by a tilde (~) symbol.
We know that if a destructor is not provided, the compiler will generate one. This means that anything beyond simple cleanup, such as primitive types, will require a destructor. In many cases, dynamic allocation or resource acquisition during construction, has a clean up phase.
A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object. Syntax of Destructor ~class_name() { //Some code }
Everybody thinks about garbage collection the wrong way:
A correctly-written program cannot assume that finalizers will ever run.
I think based on reading your almost duplicate topic that you don't have a well understanding of how the Garbage Collector works. In a very blunt and brief manner, it is its own service that runs in the background, it tracks and frees memory for unused and disposed objects throughout the entire lifetime of your application. Realistically, you should never have to call the GC yourself, unless in very rare and specific cases.
The desctructors are used to clean up and free unmanaged resources that cannot be freed by the Garbage Collector, see this MSDN page for more information on destructors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With