C# Destructor

February 24th, 2010 in C# Language by admin 0

As C# has an inbuilt garbage collection it is not necessary to explicitly destroy your objects. However, for objects which control unmanaged resources, these resources need to be explicitly freed when they are no longer require. In C#, implicit control over unmanaged resources is provided by a destructor, which can be called by the garbage collector when an object is destroyed.

A destructor only releases resources that an object holds on to, and shouldn’t reference any other objects. If all references are managed , you should not implement a destructor; you want this only for handling unmanaged resources. A destructor should only be implemented on methods that methods that consume valuable unmanaged resources.







An object’s destructor cannot be called directly, the garbage collector will always call it.

How Destructors Work in C#

The garbage collector keeps a listing of all objects that have a destructor which is updated every time such an object is created or destroyed.

When an object on the listing is first collected, it is put in a queue with the other objects waiting to be destroyed. After the destructor has executed, the garbage collector collects the object, updates the queue, and the listing of all destructible objects.

Syntax

The C# destructor looks very similar to the  C

View the Original article