Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of destructor in c#?

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 ?

like image 913
Nishant Kumar Avatar asked Sep 06 '10 04:09

Nishant Kumar


People also ask

Why do we use destructor in OOP?

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.

Is there destructor in C?

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.

Is destructor needed?

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.

What is destructor and syntax?

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 }


2 Answers

Everybody thinks about garbage collection the wrong way:

A correctly-written program cannot assume that finalizers will ever run.

like image 191
Remus Rusanu Avatar answered Sep 28 '22 12:09

Remus Rusanu


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.

like image 22
David Anderson Avatar answered Sep 28 '22 13:09

David Anderson